Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 单个主干模型实例能否同时在两个集合中?_Backbone.js - Fatal编程技术网

Backbone.js 单个主干模型实例能否同时在两个集合中?

Backbone.js 单个主干模型实例能否同时在两个集合中?,backbone.js,Backbone.js,我知道它的“this.collection”值将只显示第一个集合,但这是否与主干兼容?还是会自动从以前的收藏中删除 var MyModel = Backbone.Model.extend({defaults: {test: '123'}}); var MyCollection1 = Backbone.Collection.extend({model: MyModel}); var MyCollection2 = Backbone.Collection.extend({model: MyModel

我知道它的“this.collection”值将只显示第一个集合,但这是否与主干兼容?还是会自动从以前的收藏中删除

var MyModel = Backbone.Model.extend({defaults: {test: '123'}});
var MyCollection1 = Backbone.Collection.extend({model: MyModel});
var MyCollection2 = Backbone.Collection.extend({model: MyModel});

var instance = new MyModel({
    test: '456'
});
MyCollection1.add(instance);
MyCollection2.add(instance);

console.log(instance.collection); //Returns "MyCollection1" only, not an array of all collections of which this model is a member

上面的代码是有效的,我只是想知道这样做是否破坏了任何东西(特别是与事件相关的东西)。

TL;DR Nothing将不会中断,您可以通过查看源代码来验证这一点,
add
set(model,{add:true,remove:false,merge:false})的简写方法。

如果你看它所在的部分

因此,如果模型集合已经有一个集合,则不会将其设置为新集合,但所有事件仍将从添加到的所有集合中正确传递

反之亦然,任何集合事件都是通过迭代集合中的模型来调用的

 for (i = 0, l = models.length; i < l; i++) {
    ...
    if (!options.silent) {
      model.trigger('remove', model, this, options);
    }
    ...
  }
for(i=0,l=models.length;i
您能详细描述一下您的问题吗?当然,尽管我是在一般意义上问,而不是在特定情况下问。主干模型是否提供集合属性?这方面的用例是什么?这在技术上是允许的,但我不明白你为什么要这么做。在这次提交中添加了对多个集合中的模型的更好支持:
 for (i = 0, l = models.length; i < l; i++) {
    ...
    if (!options.silent) {
      model.trigger('remove', model, this, options);
    }
    ...
  }