Asked By: Anonymous
Is there a way to add a change event listener to browser localstorage items.
I have a standalone app that makes changes to localstorage to which I want my backbone view to listen to and accordingly perform some actions.
I couldn’t find anything on the internet except for a way to do it in jQuery:
$(window).bind('storage', function (e) {
console.log(e.originalEvent.key, e.originalEvent.newValue);
});
Solution
Answered By: Anonymous
jQuery can bind to the storage
event (in the exact way you wrote), however there are a few things you must note:
- You must run the code behind a real ip/domain (you can read more my explanation here)
- The
storage
event will fire on every open tab except the current tab (which mean – if you have only 1 open tab, and you make some change to the local-storage in that tab – the even will not fire). More information here.
Regarding backbone – try something like this:
var SomeView = Backbone.View.extend({
initialize:function() {
$(window).on("storage", this.handleLocalStorageChange)
}
});