I've extended a model A and a collection of As as follows:
define(['underscore', 'backbone', 'backbone.localStorage'], function(_, Backbone) {
var A = Backbone.Model.extend({
initialize: function() {
}
});
var A_Collection = Backbone.Collection.extend({
model: A,
localStorage: new Backbone.LocalStorage("as")
});
return {
Model: A,
Collection: A_Collection
};
});
Collections are stored in localStorage and all works fine in my application. Then I clear and replace the localStorage directly by code (using clear and setItem functions) and try to instantiate a new collection, but the changes are not detected:
var aux = new A.Collection();
aux.fetch();
// aux is empty
Otherwise if a try:
var aux = new A.Collection();
aux.localStorage = new Backbone.LocalStorage("as");
aux.fetch();
// aux contains new data
The latter is not valid for me because I'd have to modify all the creation of collections in my project.
What am I missing?
Instances of
Backbone.LocalStorageare not designed to listen forLocalStoragechanges that occur outside their own code. That's why you get the behavior you are getting. However, there is a workaround.When you define a collection like this:
the
localStoragevalue is shared by all the instances ofA_Collection. You can automatically create a new instance ofBackbone.LocalStorage, like this:We have to set it on the prototype so that it is shared by all instance of
A_Collection, which is the same behavior as your original code. With this in place, whenever you create a new instance ofA_Collection, you will get a new instance ofBackbone.LocalStorage, which will get information anew fromLocalStorage.Here is a plunker illustrating. Here is the relevant code, for reference:
The code above generates this on the console: