骨干过滤

Dav*_*ing 5 javascript collections models backbone.js underscore.js

如果我有一个Backbone集合并想要创建该集合的副本并过滤掉某些条目,那么如何在将复制的实例保持为Backbone.Collection的同时执行此操作?

例:

var Module = Backbone.Model.extend();

var ModuleCollection = Backbone.Collection.?extend({
    model: Module
});

?var modules = new ModuleCollection;

?modules.add({foo: 'foo'??????},{foo: 'bar'});?????

console.log(modules instanceof Backbone.Collection); // true

var filtered = modules.filter(function(module) {
    return module.get('foo') == 'bar';
});

console.log(filtered instanceof Backbone.Collection); // false
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/m9eTY/

在上面的例子中,我想filtered成为模块的过滤版本,而不仅仅是模型数组.

本质上我想在集合实例中创建一个可以过滤掉某些模型并返回Backbone.Collection实例的方法,但是一旦我开始过滤,迭代方法就会返回一个数组.

Vin*_*lia 9

如果需要,可以将过滤后的数组包装在临时ModuleCollection中,过滤的模型与原始ModuleCollection中的模型相同,因此如果模块的属性发生更改,则两个集合仍会引用它.

所以我建议你做的是:

var filtered = new ModuleCollection(modules.filter(function (module) {
    return module.get('foo') == 'bar';
}));
Run Code Online (Sandbox Code Playgroud)

从Backbone 0.9.2开始,还有另一个调用方法where:

var filtered = modules.where({foo: 'bar'});
Run Code Online (Sandbox Code Playgroud)

虽然仍然返回一个数组,所以你仍然需要包装它:

var filtered = new ModuleCollection(modules.where({foo: 'bar'}));
Run Code Online (Sandbox Code Playgroud)