A helper function to persist a value in local storage and update if that item is changed by another open window.
// 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