User:Quarl/wikistate.js

From Wikipedia, the free encyclopedia

If a message on your talk page led you here, please be wary of who left it. Code that you insert on this page could contain malicious content capable of compromising your account. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. If this is a .js page, the code will be executed when previewing the page.
Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.
// [[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);
}
 
addOnloadHook(wikistate._load);
 
// </nowiki></pre>