如果作为模型的 属性 传递,则集合不保存模型

collection not saving model if passed as property of model

我试图在不使用全局集合变量的情况下创建一个 Backbone 应用程序。这就是我的意思。最初,我创建了一个模型并将其添加到我视图中函数中的这样一个集合中

   this.mymodel = new MyModel();
   this.mymodel.addToCollection();

addToCollection() 函数(在模型实例上调用)中,我添加了模型实例(由 this 表示),然后在其上调用了 save

addToCollection(){
  mycollectionglobalvariable.add(this) //this global collection variable was created on application init
  this.save();
}

在集合中,我将它设置为保存到 localStorage 并且一切正常,除了我不想为集合使用全局变量(主要是为了使测试更容易),所以在我的主要view 我通过集合 属性 传递集合(这意味着我将集合传递给主视图并将其设置为 this.mycollection 属性)

    this.mymodel = new MyModel(collection: this.mycollection);

现在,在该模型的构造函数中,我设置了集合 属性

   constructor(options){
      this.collection = options.collection;
   }

addToCollection 方法现在是这样的

 addToCollection(){
   this.collection.add(this);
   this.save();
 }

结果是模型被添加到集合中但没有被保存。当我将集合作为模型的 属性 传递时,为什么模型没有被保存?

您可以看到 here in the Backbone docs 它支持将集合作为 属性 传递。

看起来您只是简单地覆盖了构造函数。您可能也应该调用默认构造函数:Backbone.Model.apply(this, arguments);.

然而,请查看模型构造函数的源代码:http://backbonejs.org/docs/backbone.html#section-53。它已经将集合选项添加到模型中,因此您可以完全删除构造函数。

var Model = Backbone.Model = function(attributes, options) {
  var attrs = attributes || {};
  options || (options = {});
  this.cid = _.uniqueId(this.cidPrefix);
  this.attributes = {};
  if (options.collection) this.collection = options.collection;
  if (options.parse) attrs = this.parse(attrs, options) || {};
  attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
  this.set(attrs, options);
  this.changed = {};
  this.initialize.apply(this, arguments);
};

最后,这可能只是一个拼写错误,但您应该将选项哈希作为第二个参数传递给您的模型。

this.mymodel = new MyModel({}, {collection: this.mycollection});

查看此 jsfiddle 示例:http://jsfiddle.net/mfze3abg/