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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/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中id数组的筛选器返回集合列表_Backbone.js - Fatal编程技术网

使用backbone.js中id数组的筛选器返回集合列表

使用backbone.js中id数组的筛选器返回集合列表,backbone.js,Backbone.js,所以我已经使用循环实现了这一点,但我想知道是否有更干净的方法来实现这一点 基本上我得到了一个模型,该模型从另一个模型获得了一个id数组,目前我循环每个id,并使用模型集合上的这个过滤器手动将模型添加到一个新集合中 getOneById : function(id){ return this.filter(function(data) { return data.get("id") == id; }); }, 有没有一种方法可以直接返回一个列表 getAllByI

所以我已经使用循环实现了这一点,但我想知道是否有更干净的方法来实现这一点

基本上我得到了一个模型,该模型从另一个模型获得了一个id数组,目前我循环每个id,并使用模型集合上的这个过滤器手动将模型添加到一个新集合中

getOneById : function(id){
    return this.filter(function(data) {
        return data.get("id") == id;
    });
},
有没有一种方法可以直接返回一个列表

getAllById : function(arrayIds){
    return _(this.filter(function(data) {
        ??????? return data.get("id") == eachID;
    }));
},

谢谢

通过检查对象的id是否位于数组中的索引>-1,可以减少循环:

function(arrayIds){
  var models = _.select(collection, function(model){
    return (_.indexOf(arrayIds, model.id) > -1);
  });
  return models;
}

这需要在代码中包含下划线.js,但由于您已经在使用主干,因此您已经有了它。

您可以通过检查对象的id是否位于数组中的索引>-1来减少循环:

function(arrayIds){
  var models = _.select(collection, function(model){
    return (_.indexOf(arrayIds, model.id) > -1);
  });
  return models;
}
这需要在代码中包含underline.js,但由于您已经在使用主干网,您已经有了它。

我的解决方案:

具有集合(主干.集合)和阵列ID

var collection2 = new Backbone.Collection();
collection2.add(collection.models.filter(function(model){
    return arrayIds.indexOf(model.id) !== -1;
}));
四行:D

console.assert(collection2.length === arrayIds.length)  //OK
我的解决方案:

具有集合(主干.集合)和阵列ID

var collection2 = new Backbone.Collection();
collection2.add(collection.models.filter(function(model){
    return arrayIds.indexOf(model.id) !== -1;
}));
四行:D

console.assert(collection2.length === arrayIds.length)  //OK

我认为应该读
collection.models
而不是
collection
我认为应该读
collection.models
而不是
collection