2

我如何比较主干中的两个集合?

我有两个集合 1C 包含1,2,3而 2C 包含2,4,5我想要做的是2从 2C 中删除,因为 1C 在通常呈现集合之后已经具有值 2。

我试过这个

this.1C.each(function(model1){
  this.2C.each(function(model2){
     if(model1 === model2){
        2C.remove(model2);
     }
  });
});

但它不起作用。有任何想法吗?

4

7 回答 7

5

你有一个叫做差异运算符http://underscorejs.org/#difference的东西。您可以使用如下

var x = _.difference([1,2,3,4],[1,2]); console.log(x); //gives [3,4]

在您的情况下,您可能应该这样做

var reducedCollection = _.difference(this.1C.toJSON(),this.2C.toJSON());

现在将提供预期的结果

于 2012-05-22T10:02:37.533 回答
4

我会冒险猜测 model1 和 model2 永远不是模型的同一个实例,因此永远不会匹配。您是否尝试过比较模型 ID 或类似的?例如。模型1.id == 模型2.id

也许添加一些调试,这样你就可以看到发生了什么..

this.1C.each(function(model1){
  console.log('m1:'+model1.categoryCode);
  this.2C.each(function(model2){
     console.log('  m2:'+model2.categoryCode);
     if(model1.categoryCode == model2.categoryCode){
        console.log('removing m2:'+model2.categoryCode);
        2C.remove(model2);
     }
  });
});
于 2012-05-22T10:07:51.603 回答
1

我为基于事件的集合比较编写了一个库。基本上,我认为你可以像这样使用这个库来实现你正在寻找的结果(没有测试过这个特定的案例):

cocomp = new Backbone.CoComp({
  comparator: function(obj) {
    obj["1C"] === obj["2C"]
  }
});

// Listen for "cocomp:in:1C" on the 2C collection. This will be
// triggered if there is a match based on the comparator above.
2C.on("cocomp:in:1C", function(value) {
  2C.remove(value);
});

cocomp.set("1C", 1C)
cocomp.set("2C", 2C)

GitHub 存储库在这里:https ://github.com/davidbiehl/backbone.cocomp

让我知道这是否有帮助!这个库的额外好处是,如果 1C 或 2C 发生变化(添加、删除或重置),如果匹配,将触发事件,有效地保持 1C 和 2C 同步。

于 2013-09-05T05:04:23.787 回答
1

代理的Underscore 方法可以在这里为您提供帮助。尝试:

2C.without(1C.models);

without并且其他代理方法返回数组,因此您必须将结果包装在另一个Backbone.Collection.

于 2012-05-22T09:57:20.000 回答
1

这对我有用:

2C.remove(1C.models);

(如果模型ID是比较检查的基础)

于 2014-05-10T06:06:42.397 回答
0

此代码中的函数 updateCollection https://github.com/3-16/Backbone-poller/blob/master/pusher.js非常适合我比较两个集合。

于 2012-12-09T22:15:08.363 回答
0
var checked = [];

arrNewCollection.forEach(function(item){ //get new collection
         if (!_.findWhere(arrOldCollection, {id: item.id})) { // find in old collection our property
                checked.push(item.id); // if in old collection can not find property then add this property in array
         }
    });
于 2016-07-22T10:43:48.193 回答