Backbone Collections

by Scott Currell

HTML

<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.min.js"></script>

JavaScript

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'); //...