简体   繁体   English

Backbone:同步模型和本地存储

[英]Backbone: synchronizing Models and LocalStorage

I've extended a model A and a collection of As as follows:我已经扩展了一个模型 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 
   };
});

Collections are stored in localStorage and all works fine in my application.集合存储在 localStorage 中,并且在我的应用程序中一切正常。 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:然后我直接通过代码清除并替换 localStorage(使用 clear 和 setItem 函数)并尝试实例化一个新集合,但未检测到更改:

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.LocalStorage are not designed to listen for LocalStorage changes that occur outside their own code. Backbone.LocalStorage实例并非旨在侦听在其自身代码之外发生的LocalStorage更改。 That's why you get the behavior you are getting.这就是为什么你会得到你正在得到的行为。 However, there is a workaround.但是,有一个解决方法。

When you define a collection like this:当你像这样定义一个集合时:

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

the localStorage value is shared by all the instances of A_Collection . localStorage值由A_Collection所有实例共享。 You can automatically create a new instance of Backbone.LocalStorage , like this:您可以自动创建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");
  },
});

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.我们必须在原型上设置它,以便它被A_Collection的所有实例共享,这与您的原始代码的行为相同。 With this in place, whenever you create a new instance of A_Collection , you will get a new instance of Backbone.LocalStorage , which will get information anew from LocalStorage .有了这个,每当您创建A_Collection的新实例时,您将获得Backbone.LocalStorage的新实例,它将从LocalStorage重新获取信息。

Here is a plunker illustrating.这是一个plunker说明。 Here is the relevant code, for reference:下面是相关代码,供参考:

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

The code above generates this on the console:上面的代码在控制台上生成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM