cyu
6/22/2010 - 2:49 AM

Bespin Plugin that Saves Settings to HTML5 localStorage

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;
    }
};