Another way in which several of the Underscore
methods can be used is by extracting a specific Model
or Models
from a Collection
. The simplest way to do this is with the where
and findWhere
methods, which return all the (or in the case of findWhere
, the first) Models that match a provided attributes object. For example, if you want to extract all the books in a Collection, which have exactly one hundred pages, you can use the where
method, as shown here:
var books = new Backbone.Collection([ { pages: 100, title: "Backbone Essentials 5: The Essentials Return" }, { pages: 100, title: "Backbone Essentials 6: We're Not Done Yet?" },{ pages: 25, title: "Completely Fake Title" } ]); var hundredPageBooks = books.where({pages: 100}); // hundredPageBooks array of all of the books except Completely Fake Title var firstHundredPageBook = books.findWhere({pages: 100}); firstHundredPageBook; // Backbone Essentials 5: The Essentials Return
What if we need a more complicated selection? For instance, what if instead of extracting all the books with exactly a hundred pages, we wanted to extract any book with a hundred or more pages? For this sort of extraction, we can use the more powerful filter
method, or its inverse, the reject
method, instead:
var books = new Backbone.Collection([ { pages: 100, title: "Backbone Essentials 5: The Essentials Return" }, { pages: 200, title: "Backbone Essentials 7: How Are We Not Done Yet?" }, { pages: 25, title: "Completely Fake Title" } ]); var hundredPageOrMoreBooks = books.filter(function(book) { return book.get('pages') >= 100; }); hundredPageOrMoreBooks; // again, this will be an array of all books but the last var hundredPageOrMoreBooks = books.reject(function(book) { return book.get('pages') < 100; }); hundredPageOrMoreBooks; // this will still be an array of all books but the last
18.119.28.108