some Underscore methods 合并到集合中有点不完美。当你说collection.some_mixed_in_underscore_method() 时,集合会在你背后解开一些 Backbone 的东西,以便将 Underscore 方法应用于集合模型内的属性;它的工作原理是这样的:
var ary = _(this.models).map(function(m) { return m.attributes });
return _(ary).some_mixed_in_underscore_method();
但是collection.chain() 不是这样工作的,chain 只是直接包装集合的models 所以如果你这样做:
console.log(collection.chain());
您会看到chain 为您提供了一个包含模型数组的对象。您的模型将没有is_checked 属性(即没有model.is_checked),但它们将具有is_checked 属性(即将有model.get('is_checked') 和model.attributes.is_checked)。
现在我们可以看到哪里出了问题:
collection.chain().where({'is_checked':true})
模型没有is_checked 属性。特别是,不会有任何模型,其中is_checked 是true 并且where 之后的所有内容都使用空数组。
既然我们知道事情的发展方向,那我们该如何解决呢?好吧,您可以使用filter 而不是where,这样您就可以轻松解压模型:
collection.chain()
.filter(function(m) { return m.get('is_checked') })
.pluck('id')
.value();
但是,您的模型还没有 ids,因为您没有使用 ids 创建它们,并且您还没有与服务器交谈以获取 ids,因此您将获得一组undefineds 返回。如果你添加一些ids:
var collection = new App.OptionCollection([
{id: 1, 'is_checked': true},
{id: 2, 'is_checked': true},
{id: 3, 'is_checked': false}
]);
然后你会得到你正在寻找的[1,2]。
演示:http://jsfiddle.net/ambiguous/kRmaD/