Backbone:同步Models和LocalStorage

时间:2016-09-16 17:22:26

标签: javascript backbone.js local-storage backbone-local-storage

我扩展了模型A和As的集合,如下所示:

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 
   };
});

集合存储在localStorage中,并且在我的应用程序中一切正常。然后我清除并直接用代码替换localStorage(使用clear和setItem函数)并尝试实例化一个新集合,但是没有检测到更改:

var aux = new A.Collection();
aux.fetch(); 
// aux is empty

否则如果尝试:

var aux = new A.Collection();
aux.localStorage = new Backbone.LocalStorage("as");
aux.fetch(); 
// aux contains new data 

后者对我无效,因为我必须修改项目中所有集合的创建。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

Backbone.LocalStorage的实例并非旨在侦听在自己的代码之外发生的LocalStorage更改。这就是为什么你得到你正在获得的行为。但是,有一种解决方法。

定义这样的集合时:

var A_Collection = Backbone.Collection.extend({
   model: A,
   localStorage: new Backbone.LocalStorage("as")
});

localStorage的所有实例共享A_Collection值。您可以自动创建Backbone.LocalStorage的新实例,如下所示:

var A_Collection = Backbone.Collection.extend({
  model: A,
  initialize: function() {
    A_Collection.__super__.initialize.apply(this, arguments);
    A_Collection.prototype.localStorage = new Backbone.LocalStorage("as");
  },
});

我们必须在原型上设置它,以便它由A_Collection的所有实例共享,这与原始代码的行为相同。有了这个,每当您创建A_Collection的新实例时,您将获得Backbone.LocalStorage的新实例,该实例将从LocalStorage重新获取信息。

这是一个plunker说明。以下是相关代码,供参考:

var A = Backbone.Model.extend({
  initialize: function() {}
});

var A_Collection = Backbone.Collection.extend({
  model: A,
  initialize: function() {
    A_Collection.__super__.initialize.apply(this, arguments);
    A_Collection.prototype.localStorage = new Backbone.LocalStorage("as");
  },
});

// Setup a collection.
var collection = new A_Collection();
collection.fetch();

// Clean it out from previous runs... Note that we have to use destroy to destroy all items. 
// Reset won't save to LocalStorage.
while (collection.length > 0) {
  var model = collection.at(0);
  model.destroy();
  collection.remove(model);
}
// and set some elements.
collection.create({
  name: "1"
});
collection.create({
  name: "2"
});
console.log("collection length:", collection.length);

// Mess with it outside the Backbone code.
localStorage.clear();
// Manually create data that looks like what Backbone expects.
localStorage.setItem("as-1", JSON.stringify({
  name: "foo",
  id: "1"
}));
localStorage.setItem("as-2", JSON.stringify({
  name: "bar",
  id: "2"
}));
localStorage.setItem("as-3", JSON.stringify({
  name: "baz",
  id: "3"
}));
localStorage.setItem("as", "1,2,3");

// Create a new collection that loads from LocalStorage
var collection2 = new A_Collection();
collection2.fetch();
console.log("collection 2 length:", collection2.length);
console.log("first item", collection2.at(0).toJSON());
console.log("third item", collection2.at(2).toJSON());

console.log("instance is shared?", collection.localStorage === collection2.localStorage);

上面的代码在控制台上生成:

collection length: 2
collection 2 length: 3
first item Object {name: "foo", id: "1"}
third item Object {name: "baz", id: "3"}
instance is shared? true