-
Notifications
You must be signed in to change notification settings - Fork 673
Description
I use localStorage collection, works great. But I want use storage event for updating collection in many tabs. Idea: do fetch() when storage event fires.
bindStorageEvent : function() {
var _this = this;
$(window).on('storage.'+this.localStorage.name, function(e) {
if(e.originalEvent.key === _this.localStorage.name) {
_this.fetch();
}
});
},
unbindStorageEvent : function() {
$(window).off('storage.'+this.localStorage.name);
}
But this shouldn't work as expetcted because records property will not be updated with fetch and save() method use records prop. And so all actual data which came from one tab will be rewrited by old data from another tab.
So I rewrited code in this way:
bindStorageEvent : function() {
var _this = this;
$(window).on('storage.'+this.localStorage.name, function(e) {
if(e.originalEvent.key === _this.localStorage.name) {
// the dirtiest records update way, only for test
var store = _this.localStorage.localStorage().getItem(_this.localStorage.name);
_this.localStorage.records = (store && store.split(",")) || [];
_this.fetch();
}
});
},
unbindStorageEvent : function() {
$(window).off('storage.'+this.localStorage.name);
}
And it works great.
Suggested solution: I think that we can put this code to the another method in the localStorage object (records_update) and call this method from constructor and from Backbone.sync() when doing fetch() or from findAll() before getting particular model. I think this property must be updated on fetch, not only at the collection initialization time.