Reputation: 1877
I need to do a simple check to see if a model already exists.
In SQL I would return the result set and cross reference it with a temp variable. How can I do the equivalent in backbone.js?
Upvotes: 0
Views: 119
Reputation: 106385
There's a direct equivalent - Collection#where method:
Return an array of all the models in a collection that match the passed attributes.
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
var musketeers = friends.where({job: "Musketeer"});
alert(musketeers.length); // 3
For more complex queries use Collection#filter:
var musketeersWhoseNameStartsWithA = friends.filter(function(item) {
return item.get('name').indexOf('A') === 0;
});
Upvotes: 1