Created
April 28, 2013 17:05
-
-
Save benfoxall/5477514 to your computer and use it in GitHub Desktop.
A helper function to persist a value in local storage and update if that item is changed by another open window.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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