Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rictorres
Forked from benfoxall/storageProxy.js
Created May 14, 2014 07:56
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 rictorres/9d1d42781940dd4e89c0 to your computer and use it in GitHub Desktop.
Save rictorres/9d1d42781940dd4e89c0 to your computer and use it in GitHub Desktop.
// helper function to persist the
// changes to localStorage and
function storageProxy(key, updateFn){
var store = window.localStorage;
// udpate if the key is already set
var initial = store.getItem(key);
if(initial) updateFn(initial)
// listen for updates from other windows
window.addEventListener("storage", function(e){
if(e.key == key) updateFn(e.newValue);
}, false);
// return a handle to update for this window
return function(obj){
store.setItem(key,JSON.stringify(obj));
updateFn(obj);
}
};
// usage :
// <a class="bgc" href="#f08">pink</a><a class="bgc" href="#08f">blue</a>
//
// Background color will be persisted, and updated across all open windows
var bgColor = storageProxy('c-key', function(c){
document.body.style.backgroundColor = c;
});
$(document).on('click', '.bgc', function(){
bgColor($(this).attr('href'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment