Created
June 22, 2010 02:49
-
-
Save cyu/447859 to your computer and use it in GitHub Desktop.
Bespin Plugin that Saves Settings to HTML5 localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"define metadata"; | |
({ | |
"dependencies": { | |
"settings": "0.0.0" | |
} | |
}); | |
"end"; | |
var console = require('bespin:console').console; | |
var Trace = require('bespin:util/stacktrace').Trace; | |
/** | |
* Save the settings to localStorage. | |
* @class | |
*/ | |
exports.LocalStoragePersister = function() { | |
}; | |
exports.LocalStoragePersister.prototype = { | |
_loading: false, | |
loadInitialValues: function(settings) { | |
var data; | |
try { | |
var contents = localStorage.settings; | |
data = JSON.parse(contents); | |
} catch (e) { | |
console.error('Unable to parse settings: ' + e); | |
data = {}; | |
} | |
this._loading = true; | |
for (var setting in data) { | |
try { | |
settings.set(setting, data[setting]); | |
} catch (ex) { | |
var trace = new Trace(ex, true); | |
console.group('Error loading settings'); | |
console.error('Attempting ', setting, '=', data[setting]); | |
console.error(ex); | |
trace.log(3); | |
console.groupEnd(); | |
} | |
} | |
this._loading = false; | |
}, | |
persistValue: function(settings, key, value) { | |
// when we're in the middle of setting the initial values, | |
// we don't care about change messages | |
if (this._loading) { | |
return; | |
} | |
// Aggregate the settings into a file | |
var data = {}; | |
settings._getSettingNames().forEach(function(key) { | |
data[key] = settings.get(key); | |
}); | |
try { | |
var settingsString = JSON.stringify(data); | |
} catch (e) { | |
console.error('Unable to JSONify the settings! ' + e); | |
return; | |
} | |
localStorage.settings = settingsString; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment