Trunk Filtration

If I have a Backbone assembly and you want to create a copy of this collection with filtered segments, how can I do this by saving the copied instance as Backbone.Collection?

Example:

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

http://jsfiddle.net/m9eTY/

In the above example, I would like it to filteredbe a filtered version of the modules, not just an array of models.

Essentially, I would like to create a method on an instance of a collection that can filter out specific models and return an instance Backbone.Collection, but as soon as I start filtering, iteration methods return an array.

+5
source share
2 answers

ModuleCollection, , - , ModuleCollection, , , - .

- :

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

Backbone 0.9.2 where, :

var filtered = modules.where({foo: 'bar'});

, :

var filtered = new ModuleCollection(modules.where({foo: 'bar'}));
+9

,

var MyCollection = Backbone.Collection.extend ({
  filtered : function () { 

UnderScore, true valid false true, true - , . this.models, , model.get(''), ,

var results = _.filter( this.models, function ( model ) {           
    if ( model.get('foo') == 'bar' ) 
    return true ; 
    return false ;
});

, JSON, , , .

results = _.map( results, function( model ) { return model.toJSON()  } );

, ,

return new Backbone.Collection( results ) ;
0

All Articles