S.Dan
S.Dan

Reputation: 1912

How to use backbone collections to filter models

I have implemented an app with multiple models and views but collections are a bit troublesome to understand. So far I have achieved my goals without the use of collections and now I am required to manipulate a set of models based on the attributes. And I'm pretty sure I need collections now.

I have the following structure(which is way simpler than the actual implementation):

app.Connector=Backbone.Model.extend({
    line: //a d3 line object
    source: //a d3 group
    target: //a d3 group  
    // and some functions
});

app.Set=Backbone.Collections.extend({
    model:app.Connector;
    url:"/set"  //what is the purpose of url?
});

var set=new app.Set();
//multiple connectors are initialized 

Say I have a d3 object obj. How can I get a list/array of the Connectors that have obj as the target?

Upvotes: 0

Views: 45

Answers (1)

Eric Guan
Eric Guan

Reputation: 15982

var filtered = set.filter(d=>d.get('target') == obj)

I find the Backbone get functions to be too verbose, so i like to transform the collection into json before filtering.

var filtered = _.filter(set.toJSON(),d=>d.target == obj)

Upvotes: 2

Related Questions