2011-06-22 86 views
6

我有一个Backbone.Collection充满模型;让我们说这个模型是Car。这个集合是一个伟大的大列表Cars。我希望能够从列表中选择几个特定的​​车辆ID,然后才能从这个集合中获得所选的车辆对象。Backbone.js:如何通过模型ID数组筛选对象集合?

我的代码块下面不工作;我确定有一种方法可以用Backbone.js/Underscore.js来做到这一点......我对Backbone/Underscore也很新鲜。

CarList = Backbone.Collection.extend({ 
    model: Car, 
    filterWithIds: function(ids) { 
     return this.filter(function(aCar) { return _.contains(ids, car.id); } 
    } 
}); 

任何指针?

+1

传递给'this.filter'的匿名函数缺少返回语句。与其他一些语言(例如Ruby)不同,JavaScript不使用函数中的最后一个表达式作为默认返回值。 (另外,将'this'分配给'coll'的行是多余的。) –

+0

你是对的,Niall ...我是用眼球来翻译我的代码,并且把它留下了;并在简化我的代码,我不小心留下了冗余线。我已经修复了我的代码示例。 –

回答

12

好的,我想我已经明白了。它接近我的原始代码块,但更新的filterWithIds函数在这里。

filterWithIds: function(ids) { 
    return _(this.models.filter(function(c) { return _.contains(ids, c.id); })); 
} 

对于那些在CoffeeScript(我)的人来说,这里是CoffeeScript版本。

filterWithIds: (ids) -> _(@models.filter (c) -> _.contains ids, c.id) 

这是我的答案;任何代码味道?

+2

而不是使用include,你可以尝试'c.id in ids'这个条件,将coffeescript变成一个for循环来检查每个id对c.id. – c3rin

+3

自从这个答案发布后,'include'被重命名为'contains'。 – hughes

+0

谢谢,@ hughes。固定! –