Jump to content

User:Quarl/wikistate.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// [[User:Quarl/wikistate.js]] - utilities to keep track of session state

// Session state persists THROUGHOUT THIS SESSION, on THIS PAGE ONLY

// * Currently works with back/forward/refresh, but not with navigating anew.

// Usage:
//     wikistate.set('foo', 123);
//     alert("foo = " + wikistate.get('foo'));

// quarl 2006-02-05 initial version

// <pre><nowiki>

document.write('<form style="display: none;" id="wikiState_sessionform">'+
               '<textarea id="wikiState_data"></textarea></form>');

wikistate = new Object();

wikistate._load = function() {
    wikistate._dataNode = document.getElementById('wikiState_data');
    wikistate._dataString = wikistate._dataNode.value || '';
    wikistate._data = wikistate._deserialize(wikistate._dataString) || {};
}

wikistate.save = function() {
    wikistate._dataString = wikistate._serialize(wikistate._data);
    wikistate._dataNode.value = wikistate._dataString;
}

wikistate.get = function(varname) {
    return wikistate._data[varname];
}

wikistate.set = function(varname, value, nosave) {
    // if (!(value instanceof String)) {
    //     alert("wikistate error: must be a string (error 5dc01aeb-2fc1-44ca-a0bd-359ec9210f46)");
    //     return;
    // }
    wikistate._data[varname] = value;
    if (!nosave) wikistate.save();
}

wikistate._serialize = function(dict) {
    return dict.toSource();
    // var r = '';
    // for (var v in dict) {
    //     var value = dict[r];
    //     if (!(value instanceof String)) continue;
    //     r += value+':'+string_quote_escape(value);
    // }
}

wikistate._deserialize = function(s) {
    // since only we can write to the form data, should be safe to evaluate
    // it.
    return eval(s);
}

$(wikistate._load);

// </nowiki></pre>