var User = Backbone.Model.extend({
url : '/users',
defaults : {
first : 'First',
last : 'Last',
email : '[email protected]'
}
});
var Users = Backbone.Collection.extend({
model : User
});
var users = new Users([
{first : 'John', last : 'Doe'},
{first : 'Jane', last : 'Doe'},
{first : 'Jeff', last : 'Doe'},
{first : 'John', last : 'Other'}
]);
users.on('change', function(model) {
console.log('model change: ', model.toJSON());
});
// console.log(users.length); // 4
// console.log(users.models);
// console.log(users.toJSON()); // Array of Collection objects
// Looks through each value in the list, returning the first
// one that passes a truth test (predicate), or undefined if
// no value passes the test. The function returns as soon as
// it finds an acceptable element, and doesn't traverse the
// entire list.
var findFirstTruthy = users.find(function(item) {
return item.get('first') === 'John';
});
console.log('findFirstTruthy: ', findFirstTruthy.toJSON());
// Looks through the list and returns the first value that
// matches all of the key-value pairs listed in properties.
// If no match is found, or if list is empty, undefined will
// be returned.
var findFirstMatch = users.findWhere({first : 'John'});
console.log('findFirstMatch: ', findFirstMatch.toJSON());
// Same as findWhere, but returns an array of matched
// models rather than the first matched model object.
// Looks through each value in the list, returning an
// array of all the values that contain all of the key-value
// pairs listed in properties.
// Can't use toJSON() on the results since it's an array.
var findAll = users.where({first : 'John'});
// console.log('findAll: ', findAll); // Returns an array of models, not a separate collection
var changeFirstMatch = users.findWhere({first : 'Jane'}); // Find first Jane
changeFirstMatch.set('first','Kate'); //...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.