Skip to content

Instantly share code, notes, and snippets.

@cyu
Created June 22, 2010 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyu/447859 to your computer and use it in GitHub Desktop.
Save cyu/447859 to your computer and use it in GitHub Desktop.
Bespin Plugin that Saves Settings to HTML5 localStorage
"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