PageRenderTime 29ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/chapters/03-internals.md

https://gitlab.com/OpenBookPlatform/backbone-fundamentals
Markdown | 2069 lines | 1503 code | 566 blank | 0 comment | 0 complexity | fb7c9d0a954a8d2e3aa2bb060493675d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # Backbone Basics
  2. In this section, you'll learn the essentials of Backbone's models, views, collections, events, and routers. This isn't by any means a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications using it.
  3. ### Getting set up
  4. Before we dive into more code examples, let's define some boilerplate markup you can use to specify the dependencies Backbone requires. This boilerplate can be reused in many ways with little to no alteration and will allow you to run code from examples with ease.
  5. You can paste the following into your text editor of choice, replacing the commented line between the script tags with the JavaScript from any given example:
  6. ```html
  7. <!DOCTYPE HTML>
  8. <html>
  9. <head>
  10. <meta charset="UTF-8">
  11. <title>Title</title>
  12. </head>
  13. <body>
  14. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  15. <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
  16. <script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
  17. <script>
  18. // Your code goes here
  19. </script>
  20. </body>
  21. </html>
  22. ```
  23. You can then save and run the file in your browser of choice, such as Chrome or Firefox. Alternatively, if you prefer working with an online code editor, [jsFiddle](http://jsfiddle.net/jnf8B/) and [jsBin](http://jsbin.com/iwiwox/1/edit) versions of this boilerplate are also available.
  24. Most examples can also be run directly from within the console in your browser's developer tools, assuming you've loaded the boilerplate HTML page so that Backbone and its dependencies are available for use.
  25. For Chrome, you can open up the DevTools via the Chrome menu in the top right hand corner: select "Tools > Developer Tools" or alternatively use the Control + Shift + I shortcut on Windows/Linux or Command + Option + I on Mac.
  26. ![](img/devtools.png)
  27. Next, switch to the Console tab, from where you can enter in and run any piece of JavaScript code by hitting the return key. You can also use the Console as a multi-line editor using the Shift + Enter shortcut on Windows, or Ctrl + Enter shortcut on Mac to move from the end of one line to the start of another.
  28. ## Models
  29. Backbone models contain data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a todo item including its attributes like title (todo content) and completed (current state of the todo).
  30. Models can be created by extending `Backbone.Model` as follows:
  31. ```javascript
  32. var Todo = Backbone.Model.extend({});
  33. // We can then create our own concrete instance of a (Todo) model
  34. // with no values at all:
  35. var todo1 = new Todo();
  36. // Following logs: {}
  37. console.log(JSON.stringify(todo1));
  38. // or with some arbitrary data:
  39. var todo2 = new Todo({
  40. title: 'Check the attributes of both model instances in the console.',
  41. completed: true
  42. });
  43. // Following logs: {"title":"Check the attributes of both model instances in the console.","completed":true}
  44. console.log(JSON.stringify(todo2));
  45. ```
  46. #### Initialization
  47. The `initialize()` method is called when a new instance of a model is created. Its use is optional; however you'll see why it's good practice to use it below.
  48. ```javascript
  49. var Todo = Backbone.Model.extend({
  50. initialize: function(){
  51. console.log('This model has been initialized.');
  52. }
  53. });
  54. var myTodo = new Todo();
  55. // Logs: This model has been initialized.
  56. ```
  57. **Default values**
  58. There are times when you want your model to have a set of default values (e.g., in a scenario where a complete set of data isn't provided by the user). This can be set using a property called `defaults` in your model.
  59. ```javascript
  60. var Todo = Backbone.Model.extend({
  61. // Default todo attribute values
  62. defaults: {
  63. title: '',
  64. completed: false
  65. }
  66. });
  67. // Now we can create our concrete instance of the model
  68. // with default values as follows:
  69. var todo1 = new Todo();
  70. // Following logs: {"title":"","completed":false}
  71. console.log(JSON.stringify(todo1));
  72. // Or we could instantiate it with some of the attributes (e.g., with custom title):
  73. var todo2 = new Todo({
  74. title: 'Check attributes of the logged models in the console.'
  75. });
  76. // Following logs: {"title":"Check attributes of the logged models in the console.","completed":false}
  77. console.log(JSON.stringify(todo2));
  78. // Or override all of the default attributes:
  79. var todo3 = new Todo({
  80. title: 'This todo is done, so take no action on this one.',
  81. completed: true
  82. });
  83. // Following logs: {"title":"This todo is done, so take no action on this one.","completed":true}
  84. console.log(JSON.stringify(todo3));
  85. ```
  86. #### Getters & Setters
  87. **Model.get()**
  88. `Model.get()` provides easy access to a model's attributes.
  89. ```javascript
  90. var Todo = Backbone.Model.extend({
  91. // Default todo attribute values
  92. defaults: {
  93. title: '',
  94. completed: false
  95. }
  96. });
  97. var todo1 = new Todo();
  98. console.log(todo1.get('title')); // empty string
  99. console.log(todo1.get('completed')); // false
  100. var todo2 = new Todo({
  101. title: "Retrieved with model's get() method.",
  102. completed: true
  103. });
  104. console.log(todo2.get('title')); // Retrieved with model's get() method.
  105. console.log(todo2.get('completed')); // true
  106. ```
  107. If you need to read or clone all of a model's data attributes, use its `toJSON()` method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When `JSON.stringify()` is passed an object with a `toJSON()` method, it stringifies the return value of `toJSON()` instead of the original object. The examples in the previous section took advantage of this feature when they called `JSON.stringify()` to log model instances.)
  108. ```javascript
  109. var Todo = Backbone.Model.extend({
  110. // Default todo attribute values
  111. defaults: {
  112. title: '',
  113. completed: false
  114. }
  115. });
  116. var todo1 = new Todo();
  117. var todo1Attributes = todo1.toJSON();
  118. // Following logs: {"title":"","completed":false}
  119. console.log(todo1Attributes);
  120. var todo2 = new Todo({
  121. title: "Try these examples and check results in console.",
  122. completed: true
  123. });
  124. // logs: {"title":"Try these examples and check results in console.","completed":true}
  125. console.log(todo2.toJSON());
  126. ```
  127. **Model.set()**
  128. `Model.set()` sets a hash containing one or more attributes on the model. When any of these attributes alter the state of the model, a "change" event is triggered on it. Change events for each attribute are also triggered and can be bound to (e.g. `change:name`, `change:age`).
  129. ```javascript
  130. var Todo = Backbone.Model.extend({
  131. // Default todo attribute values
  132. defaults: {
  133. title: '',
  134. completed: false
  135. }
  136. });
  137. // Setting the value of attributes via instantiation
  138. var myTodo = new Todo({
  139. title: "Set through instantiation."
  140. });
  141. console.log('Todo title: ' + myTodo.get('title')); // Todo title: Set through instantiation.
  142. console.log('Completed: ' + myTodo.get('completed')); // Completed: false
  143. // Set single attribute value at a time through Model.set():
  144. myTodo.set("title", "Title attribute set through Model.set().");
  145. console.log('Todo title: ' + myTodo.get('title')); // Todo title: Title attribute set through Model.set().
  146. console.log('Completed: ' + myTodo.get('completed')); // Completed: false
  147. // Set map of attributes through Model.set():
  148. myTodo.set({
  149. title: "Both attributes set through Model.set().",
  150. completed: true
  151. });
  152. console.log('Todo title: ' + myTodo.get('title')); // Todo title: Both attributes set through Model.set().
  153. console.log('Completed: ' + myTodo.get('completed')); // Completed: true
  154. ```
  155. **Direct access**
  156. Models expose an `.attributes` attribute which represents an internal hash containing the state of that model. This is generally in the form of a JSON object similar to the model data you might find on the server but can take other forms.
  157. Setting values through the `.attributes` attribute on a model bypasses triggers bound to the model.
  158. Passing `{silent:true}` on change doesn't delay individual `"change:attr"` events. Instead they are silenced entirely:
  159. ```javascript
  160. var Person = new Backbone.Model();
  161. Person.on("change:name", function() { console.log('Name changed'); });
  162. Person.set({name: 'Andrew'});
  163. // log entry: Name changed
  164. Person.set({name: 'Jeremy'}, {silent: true});
  165. // no log entry
  166. console.log(Person.hasChanged("name"));
  167. // true: change was recorded
  168. console.log(Person.hasChanged(null));
  169. // true: something (anything) has changed
  170. ```
  171. Remember where possible it is best practice to use `Model.set()`, or direct instantiation as explained earlier.
  172. #### Listening for changes to your model
  173. If you want to receive a notification when a Backbone model changes you can bind a listener to the model for its change event. A convenient place to add listeners is in the `initialize()` function as shown below:
  174. ```javascript
  175. var Todo = Backbone.Model.extend({
  176. // Default todo attribute values
  177. defaults: {
  178. title: '',
  179. completed: false
  180. },
  181. initialize: function(){
  182. console.log('This model has been initialized.');
  183. this.on('change', function(){
  184. console.log('- Values for this model have changed.');
  185. });
  186. }
  187. });
  188. var myTodo = new Todo();
  189. myTodo.set('title', 'The listener is triggered whenever an attribute value changes.');
  190. console.log('Title has changed: ' + myTodo.get('title'));
  191. myTodo.set('completed', true);
  192. console.log('Completed has changed: ' + myTodo.get('completed'));
  193. myTodo.set({
  194. title: 'Changing more than one attribute at the same time only triggers the listener once.',
  195. completed: true
  196. });
  197. // Above logs:
  198. // This model has been initialized.
  199. // - Values for this model have changed.
  200. // Title has changed: The listener is triggered whenever an attribute value changes.
  201. // - Values for this model have changed.
  202. // Completed has changed: true
  203. // - Values for this model have changed.
  204. ```
  205. You can also listen for changes to individual attributes in a Backbone model. In the following example, we log a message whenever a specific attribute (the title of our Todo model) is altered.
  206. ```javascript
  207. var Todo = Backbone.Model.extend({
  208. // Default todo attribute values
  209. defaults: {
  210. title: '',
  211. completed: false
  212. },
  213. initialize: function(){
  214. console.log('This model has been initialized.');
  215. this.on('change:title', function(){
  216. console.log('Title value for this model has changed.');
  217. });
  218. },
  219. setTitle: function(newTitle){
  220. this.set({ title: newTitle });
  221. }
  222. });
  223. var myTodo = new Todo();
  224. // Both of the following changes trigger the listener:
  225. myTodo.set('title', 'Check what\'s logged.');
  226. myTodo.setTitle('Go fishing on Sunday.');
  227. // But, this change type is not observed, so no listener is triggered:
  228. myTodo.set('completed', true);
  229. console.log('Todo set as completed: ' + myTodo.get('completed'));
  230. // Above logs:
  231. // This model has been initialized.
  232. // Title value for this model has changed.
  233. // Title value for this model has changed.
  234. // Todo set as completed: true
  235. ```
  236. #### Validation
  237. Backbone supports model validation through `model.validate()`, which allows checking the attribute values for a model prior to setting them. By default, validation occurs when the model is persisted using the `save()` method or when `set()` is called if `{validate:true}` is passed as an argument.
  238. ```javascript
  239. var Person = new Backbone.Model({name: 'Jeremy'});
  240. // Validate the model name
  241. Person.validate = function(attrs) {
  242. if (!attrs.name) {
  243. return 'I need your name';
  244. }
  245. };
  246. // Change the name
  247. Person.set({name: 'Samuel'});
  248. console.log(Person.get('name'));
  249. // 'Samuel'
  250. // Remove the name attribute, force validation
  251. Person.unset('name', {validate: true});
  252. // false
  253. ```
  254. Above, we also use the `unset()` method, which removes an attribute by deleting it from the internal model attributes hash.
  255. Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from `.validate()`. If they are invalid, an error value should be returned instead.
  256. Should an error be returned:
  257. * An `invalid` event will be triggered, setting the `validationError` property on the model with the value which is returned by this method.
  258. * `.save()` will not continue and the attributes of the model will not be modified on the server.
  259. A more complete validation example can be seen below:
  260. ```javascript
  261. var Todo = Backbone.Model.extend({
  262. defaults: {
  263. completed: false
  264. },
  265. validate: function(attributes){
  266. if(attributes.title === undefined){
  267. return "Remember to set a title for your todo.";
  268. }
  269. },
  270. initialize: function(){
  271. console.log('This model has been initialized.');
  272. this.on("invalid", function(model, error){
  273. console.log(error);
  274. });
  275. }
  276. });
  277. var myTodo = new Todo();
  278. myTodo.set('completed', true, {validate: true}); // logs: Remember to set a title for your todo.
  279. console.log('completed: ' + myTodo.get('completed')); // completed: false
  280. ```
  281. **Note**: the `attributes` object passed to the `validate` function represents what the attributes would be after completing the current `set()` or `save()`. This object is distinct from the current attributes of the model and from the parameters passed to the operation. Since it is created by shallow copy, it is not possible to change any Number, String, or Boolean attribute of the input within the function, but it *is* possible to change attributes in nested objects.
  282. An example of this (by @fivetanley) is available [here](http://jsfiddle.net/2NdDY/270/).
  283. Note also, that validation on initialization is possible but of limited use, as the object being constructed is internally marked invalid but nevertheless passed back to the caller (continuing the above example):
  284. ```javascript
  285. var emptyTodo = new Todo(null, {validate: true});
  286. console.log(emptyTodo.validationError);
  287. ```
  288. ## Views
  289. Views in Backbone don't contain the HTML markup for your application; they contain the logic behind the presentation of the model's data to the user. This is usually achieved using JavaScript templating (e.g., Underscore Microtemplates, Mustache, jQuery-tmpl, etc.). A view's `render()` method can be bound to a model's `change()` event, enabling the view to instantly reflect model changes without requiring a full page refresh.
  290. #### Creating new views
  291. Creating a new view is relatively straightforward and similar to creating new models. To create a new View, simply extend `Backbone.View`. We introduced the sample TodoView below in the previous chapter; now let's take a closer look at how it works:
  292. ```javascript
  293. var TodoView = Backbone.View.extend({
  294. tagName: 'li',
  295. // Cache the template function for a single item.
  296. todoTpl: _.template( "An example template" ),
  297. events: {
  298. 'dblclick label': 'edit',
  299. 'keypress .edit': 'updateOnEnter',
  300. 'blur .edit': 'close'
  301. },
  302. initialize: function (options) {
  303. // In Backbone 1.1.0, if you want to access passed options in
  304. // your view, you will need to save them as follows:
  305. this.options = options || {};
  306. },
  307. // Re-render the title of the todo item.
  308. render: function() {
  309. this.$el.html( this.todoTpl( this.model.attributes ) );
  310. this.input = this.$('.edit');
  311. return this;
  312. },
  313. edit: function() {
  314. // executed when todo label is double clicked
  315. },
  316. close: function() {
  317. // executed when todo loses focus
  318. },
  319. updateOnEnter: function( e ) {
  320. // executed on each keypress when in todo edit mode,
  321. // but we'll wait for enter to get in action
  322. }
  323. });
  324. var todoView = new TodoView();
  325. // log reference to a DOM element that corresponds to the view instance
  326. console.log(todoView.el); // logs <li></li>
  327. ```
  328. #### What is `el`?
  329. The central property of a view is `el` (the value logged in the last statement of the example). What is `el` and how is it defined?
  330. `el` is basically a reference to a DOM element and all views must have one. Views can use `el` to compose their element's content and then insert it into the DOM all at once, which makes for faster rendering because the browser performs the minimum required number of reflows and repaints.
  331. There are two ways to associate a DOM element with a view: a new element can be created for the view and subsequently added to the DOM or a reference can be made to an element which already exists in the page.
  332. If you want to create a new element for your view, set any combination of the following properties on the view: `tagName`, `id`, and `className`. A new element will be created for you by the framework and a reference to it will be available at the `el` property. If nothing is specified `tagName` defaults to `div`.
  333. In the example above, `tagName` is set to 'li', resulting in creation of an li element. The following example creates a ul element with id and class attributes:
  334. ```javascript
  335. var TodosView = Backbone.View.extend({
  336. tagName: 'ul', // required, but defaults to 'div' if not set
  337. className: 'container', // optional, you can assign multiple classes to
  338. // this property like so: 'container homepage'
  339. id: 'todos' // optional
  340. });
  341. var todosView = new TodosView();
  342. console.log(todosView.el); // logs <ul id="todos" class="container"></ul>
  343. ```
  344. The above code creates the DOM element below but doesn't append it to the DOM.
  345. ```html
  346. <ul id="todos" class="container"></ul>
  347. ```
  348. If the element already exists in the page, you can set `el` as a CSS selector that matches the element.
  349. ```javascript
  350. el: '#footer'
  351. ```
  352. Alternatively, you can set `el` to an existing element when creating the view:
  353. ```javascript
  354. var todosView = new TodosView({el: $('#footer')});
  355. ```
  356. Note: When declaring a View, `options`, `el`, `tagName`, `id` and `className` may be defined as functions, if you want their values to be determined at runtime.
  357. **$el and $()**
  358. View logic often needs to invoke jQuery or Zepto functions on the `el` element and elements nested within it. Backbone makes it easy to do so by defining the `$el` property and `$()` function. The `view.$el` property is equivalent to `$(view.el)` and `view.$(selector)` is equivalent to `$(view.el).find(selector)`. In our TodoView example's render method, we see `this.$el` used to set the HTML of the element and `this.$()` used to find subelements of class 'edit'.
  359. **setElement**
  360. If you need to apply an existing Backbone view to a different DOM element `setElement` can be used for this purpose. Overriding this.el needs to both change the DOM reference and re-bind events to the new element (and unbind from the old).
  361. `setElement` will create a cached `$el` reference for you, moving the delegated events for a view from the old element to the new one.
  362. ```javascript
  363. // We create two DOM elements representing buttons
  364. // which could easily be containers or something else
  365. var button1 = $('<button></button>');
  366. var button2 = $('<button></button>');
  367. // Define a new view
  368. var View = Backbone.View.extend({
  369. events: {
  370. click: function(e) {
  371. console.log(view.el === e.target);
  372. }
  373. }
  374. });
  375. // Create a new instance of the view, applying it
  376. // to button1
  377. var view = new View({el: button1});
  378. // Apply the view to button2 using setElement
  379. view.setElement(button2);
  380. button1.trigger('click');
  381. button2.trigger('click'); // returns true
  382. ```
  383. The "el" property represents the markup portion of the view that will be rendered; to get the view to actually render to the page, you need to add it as a new element or append it to an existing element.
  384. ```javascript
  385. // We can also provide raw markup to setElement
  386. // as follows (just to demonstrate it can be done):
  387. var view = new Backbone.View;
  388. view.setElement('<p><a><b>test</b></a></p>');
  389. console.log(view.$('a b').html()); // outputs "test"
  390. ```
  391. **Understanding `render()`**
  392. `render()` is an optional function that defines the logic for rendering a template. We'll use Underscore's micro-templating in these examples, but remember you can use other templating frameworks if you prefer. Our example will reference the following HTML markup:
  393. ```html
  394. <!doctype html>
  395. <html lang="en">
  396. <head>
  397. <meta charset="utf-8">
  398. <title></title>
  399. <meta name="description" content="">
  400. </head>
  401. <body>
  402. <div id="todo">
  403. </div>
  404. <script type="text/template" id="item-template">
  405. <div>
  406. <input id="todo_complete" type="checkbox" <%= completed ? 'checked="checked"' : '' %>>
  407. <%= title %>
  408. </div>
  409. </script>
  410. <script src="underscore-min.js"></script>
  411. <script src="backbone-min.js"></script>
  412. <script src="jquery-min.js"></script>
  413. <script src="example.js"></script>
  414. </body>
  415. </html>
  416. ```
  417. The `_.template` method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the TodoView, I'm passing the markup from the template with id `item-template` to `_.template()` to be compiled and stored in the todoTpl property when the view is created.
  418. The `render()` method uses this template by passing it the `toJSON()` encoding of the attributes of the model associated with the view. The template returns its markup after using the model's title and completed flag to evaluate the expressions containing them. I then set this markup as the HTML content of the `el` DOM element using the `$el` property.
  419. Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.
  420. A common Backbone convention is to return `this` at the end of `render()`. This is useful for a number of reasons, including:
  421. * Making views easily reusable in other parent views.
  422. * Creating a list of elements without rendering and painting each of them individually, only to be drawn once the entire list is populated.
  423. Let's try to implement the latter of these. The `render` method of a simple ListView which doesn't use an ItemView for each item could be written:
  424. ```javascript
  425. var ListView = Backbone.View.extend({
  426. // Compile a template for this view. In this case '...'
  427. // is a placeholder for a template such as
  428. // $("#list_template").html()
  429. template: _.template(…),
  430. render: function() {
  431. this.$el.html(this.template(this.model.attributes));
  432. return this;
  433. }
  434. });
  435. ```
  436. Simple enough. Let's now assume a decision is made to construct the items using an ItemView to provide enhanced behaviour to our list. The ItemView could be written:
  437. ```javascript
  438. var ItemView = Backbone.View.extend({
  439. events: {},
  440. render: function(){
  441. this.$el.html(this.template(this.model.attributes));
  442. return this;
  443. }
  444. });
  445. ```
  446. Note the usage of `return this;` at the end of `render`. This common pattern enables us to reuse the view as a sub-view. We can also use it to pre-render the view prior to rendering. Using this requires that we make a change to our ListView's `render` method as follows:
  447. ```javascript
  448. var ListView = Backbone.View.extend({
  449. render: function(){
  450. // Assume our model exposes the items we will
  451. // display in our list
  452. var items = this.model.get('items');
  453. // Loop through each of our items using the Underscore
  454. // _.each iterator
  455. _.each(items, function(item){
  456. // Create a new instance of the ItemView, passing
  457. // it a specific model item
  458. var itemView = new ItemView({ model: item });
  459. // The itemView's DOM element is appended after it
  460. // has been rendered. Here, the 'return this' is helpful
  461. // as the itemView renders its model. Later, we ask for
  462. // its output ("el")
  463. this.$el.append( itemView.render().el );
  464. }, this);
  465. }
  466. });
  467. ```
  468. **The `events` hash**
  469. The Backbone `events` hash allows us to attach event listeners to either `el`-relative custom selectors, or directly to `el` if no selector is provided. An event takes the form of a key-value pair `'eventName selector': 'callbackFunction'` and a number of DOM event-types are supported, including `click`, `submit`, `mouseover`, `dblclick` and more.
  470. ```javascript
  471. // A sample view
  472. var TodoView = Backbone.View.extend({
  473. tagName: 'li',
  474. // with an events hash containing DOM events
  475. // specific to an item:
  476. events: {
  477. 'click .toggle': 'toggleCompleted',
  478. 'dblclick label': 'edit',
  479. 'keypress .edit': 'updateOnEnter',
  480. 'click .destroy': 'clear',
  481. 'blur .edit': 'close'
  482. },
  483. ```
  484. What isn't instantly obvious is that while Backbone uses jQuery's `.delegate()` underneath, it goes further by extending it so that `this` always refers to the current view object within callback functions. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.
  485. The declarative, delegated jQuery events means that you don't have to worry about whether a particular element has been rendered to the DOM yet or not. Usually with jQuery you have to worry about "presence or absence in the DOM" all the time when binding events.
  486. In our TodoView example, the edit callback is invoked when the user double-clicks a label element within the `el` element, updateOnEnter is called for each keypress in an element with class 'edit', and close executes when an element with class 'edit' loses focus. Each of these callback functions can use `this` to refer to the TodoView object.
  487. Note that you can also bind methods yourself using `_.bind(this.viewEvent, this)`, which is effectively what the value in each event's key-value pair is doing. Below we use `_.bind` to re-render our view when a model changes.
  488. ```javascript
  489. var TodoView = Backbone.View.extend({
  490. initialize: function() {
  491. this.model.bind('change', _.bind(this.render, this));
  492. }
  493. });
  494. ```
  495. `_.bind` only works on one method at a time, but effectively binds a function to an object so that anytime the function is called the value of `this` will be the object. `_.bind` also supports passing in arguments to the function in order to fill them in advance - a technique known as [partial application](http://benalman.com/news/2012/09/partial-application-in-javascript/).
  496. ## Collections
  497. Collections are sets of Models and are created by extending `Backbone.Collection`.
  498. Normally, when creating a collection you'll also want to define a property specifying the type of model that your collection will contain, along with any instance properties required.
  499. In the following example, we create a TodoCollection that will contain our Todo models:
  500. ```javascript
  501. var Todo = Backbone.Model.extend({
  502. defaults: {
  503. title: '',
  504. completed: false
  505. }
  506. });
  507. var TodosCollection = Backbone.Collection.extend({
  508. model: Todo
  509. });
  510. var myTodo = new Todo({title:'Read the whole book', id: 2});
  511. // pass array of models on collection instantiation
  512. var todos = new TodosCollection([myTodo]);
  513. console.log("Collection size: " + todos.length); // Collection size: 1
  514. ```
  515. #### Adding and Removing Models
  516. The preceding example populated the collection using an array of models when it was instantiated. After a collection has been created, models can be added and removed using the `add()` and `remove()` methods:
  517. ```javascript
  518. var Todo = Backbone.Model.extend({
  519. defaults: {
  520. title: '',
  521. completed: false
  522. }
  523. });
  524. var TodosCollection = Backbone.Collection.extend({
  525. model: Todo
  526. });
  527. var a = new Todo({ title: 'Go to Jamaica.'}),
  528. b = new Todo({ title: 'Go to China.'}),
  529. c = new Todo({ title: 'Go to Disneyland.'});
  530. var todos = new TodosCollection([a,b]);
  531. console.log("Collection size: " + todos.length);
  532. // Logs: Collection size: 2
  533. todos.add(c);
  534. console.log("Collection size: " + todos.length);
  535. // Logs: Collection size: 3
  536. todos.remove([a,b]);
  537. console.log("Collection size: " + todos.length);
  538. // Logs: Collection size: 1
  539. todos.remove(c);
  540. console.log("Collection size: " + todos.length);
  541. // Logs: Collection size: 0
  542. ```
  543. Note that `add()` and `remove()` accept both individual models and lists of models.
  544. Also note that when using `add()` on a collection, passing `{merge: true}` causes duplicate models to have their attributes merged in to the existing models, instead of being ignored.
  545. ```javascript
  546. var items = new Backbone.Collection;
  547. items.add([{ id : 1, name: "Dog" , age: 3}, { id : 2, name: "cat" , age: 2}]);
  548. items.add([{ id : 1, name: "Bear" }], {merge: true });
  549. items.add([{ id : 2, name: "lion" }]); // merge: false
  550. console.log(JSON.stringify(items.toJSON()));
  551. // [{"id":1,"name":"Bear","age":3},{"id":2,"name":"cat","age":2}]
  552. ```
  553. #### Retrieving Models
  554. There are a few different ways to retrieve a model from a collection. The most straight-forward is to use `Collection.get()` which accepts a single id as follows:
  555. ```javascript
  556. var myTodo = new Todo({title:'Read the whole book', id: 2});
  557. // pass array of models on collection instantiation
  558. var todos = new TodosCollection([myTodo]);
  559. var todo2 = todos.get(2);
  560. // Models, as objects, are passed by reference
  561. console.log(todo2 === myTodo); // true
  562. ```
  563. In client-server applications, collections contain models obtained from the server. Anytime you're exchanging data between the client and a server, you will need a way to uniquely identify models. In Backbone, this is done using the `id`, `cid`, and `idAttribute` properties.
  564. Each model in Backbone has an `id`, which is a unique identifier that is either an integer or string (e.g., a UUID). Models also have a `cid` (client id) which is automatically generated by Backbone when the model is created. Either identifier can be used to retrieve a model from a collection.
  565. The main difference between them is that the `cid` is generated by Backbone; it is helpful when you don't have a true id - this may be the case if your model has yet to be saved to the server or you aren't saving it to a database.
  566. The `idAttribute` is the identifying attribute name of the model returned from the server (i.e., the `id` in your database). This tells Backbone which data field from the server should be used to populate the `id` property (think of it as a mapper). By default, it assumes `id`, but this can be customized as needed. For instance, if your server sets a unique attribute on your model named "userId" then you would set `idAttribute` to "userId" in your model definition.
  567. The value of a model's idAttribute should be set by the server when the model is saved. After this point you shouldn't need to set it manually, unless further control is required.
  568. Internally, `Backbone.Collection` contains an array of models enumerated by their `id` property, if the model instances happen to have one. When `collection.get(id)` is called, this array is checked for existence of the model instance with the corresponding `id`.
  569. ```javascript
  570. // extends the previous example
  571. var todoCid = todos.get(todo2.cid);
  572. // As mentioned in previous example,
  573. // models are passed by reference
  574. console.log(todoCid === myTodo); // true
  575. ```
  576. #### Listening for events
  577. As collections represent a group of items, we can listen for `add` and `remove` events which occur when models are added to or removed from a collection. Here's an example:
  578. ```javascript
  579. var TodosCollection = new Backbone.Collection();
  580. TodosCollection.on("add", function(todo) {
  581. console.log("I should " + todo.get("title") + ". Have I done it before? " + (todo.get("completed") ? 'Yeah!': 'No.' ));
  582. });
  583. TodosCollection.add([
  584. { title: 'go to Jamaica', completed: false },
  585. { title: 'go to China', completed: false },
  586. { title: 'go to Disneyland', completed: true }
  587. ]);
  588. // The above logs:
  589. // I should go to Jamaica. Have I done it before? No.
  590. // I should go to China. Have I done it before? No.
  591. // I should go to Disneyland. Have I done it before? Yeah!
  592. ```
  593. In addition, we're also able to bind to a `change` event to listen for changes to any of the models in the collection.
  594. ```javascript
  595. var TodosCollection = new Backbone.Collection();
  596. // log a message if a model in the collection changes
  597. TodosCollection.on("change:title", function(model) {
  598. console.log("Changed my mind! I should " + model.get('title'));
  599. });
  600. TodosCollection.add([
  601. { title: 'go to Jamaica.', completed: false, id: 3 },
  602. ]);
  603. var myTodo = TodosCollection.get(3);
  604. myTodo.set('title', 'go fishing');
  605. // Logs: Changed my mind! I should go fishing
  606. ```
  607. jQuery-style event maps of the form `obj.on({click: action})` can also be used. These can be clearer than needing three separate calls to `.on` and should align better with the events hash used in Views:
  608. ```javascript
  609. var Todo = Backbone.Model.extend({
  610. defaults: {
  611. title: '',
  612. completed: false
  613. }
  614. });
  615. var myTodo = new Todo();
  616. myTodo.set({title: 'Buy some cookies', completed: true});
  617. myTodo.on({
  618. 'change:title' : titleChanged,
  619. 'change:completed' : stateChanged
  620. });
  621. function titleChanged(){
  622. console.log('The title was changed!');
  623. }
  624. function stateChanged(){
  625. console.log('The state was changed!');
  626. }
  627. myTodo.set({title: 'Get the groceries'});
  628. // The title was changed!
  629. ```
  630. Backbone events also support a [once()](http://backbonejs.org/#Events-once) method, which ensures that a callback only fires one time when a notification arrives. It is similar to Node's [once](http://nodejs.org/api/events.html#events_emitter_once_event_listener), or jQuery's [one](http://api.jquery.com/one/). This is particularly useful for when you want to say "the next time something happens, do this".
  631. ```javascript
  632. // Define an object with two counters
  633. var TodoCounter = { counterA: 0, counterB: 0 };
  634. // Mix in Backbone Events
  635. _.extend(TodoCounter, Backbone.Events);
  636. // Increment counterA, triggering an event
  637. var incrA = function(){
  638. TodoCounter.counterA += 1;
  639. // This triggering will not
  640. // produce any effect on the counters
  641. TodoCounter.trigger('event');
  642. };
  643. // Increment counterB
  644. var incrB = function(){
  645. TodoCounter.counterB += 1;
  646. };
  647. // Use once rather than having to explicitly unbind
  648. // our event listener
  649. TodoCounter.once('event', incrA);
  650. TodoCounter.once('event', incrB);
  651. // Trigger the event for the first time
  652. TodoCounter.trigger('event');
  653. // Check out output
  654. console.log(TodoCounter.counterA === 1); // true
  655. console.log(TodoCounter.counterB === 1); // true
  656. ```
  657. `counterA` and `counterB` should only have been incremented once.
  658. #### Resetting/Refreshing Collections
  659. Rather than adding or removing models individually, you might want to update an entire collection at once. `Collection.set()` takes an array of models and performs the necessary add, remove, and change operations required to update the collection.
  660. ```javascript
  661. var TodosCollection = new Backbone.Collection();
  662. TodosCollection.add([
  663. { id: 1, title: 'go to Jamaica.', completed: false },
  664. { id: 2, title: 'go to China.', completed: false },
  665. { id: 3, title: 'go to Disneyland.', completed: true }
  666. ]);
  667. // we can listen for add/change/remove events
  668. TodosCollection.on("add", function(model) {
  669. console.log("Added " + model.get('title'));
  670. });
  671. TodosCollection.on("remove", function(model) {
  672. console.log("Removed " + model.get('title'));
  673. });
  674. TodosCollection.on("change:completed", function(model) {
  675. console.log("Completed " + model.get('title'));
  676. });
  677. TodosCollection.set([
  678. { id: 1, title: 'go to Jamaica.', completed: true },
  679. { id: 2, title: 'go to China.', completed: false },
  680. { id: 4, title: 'go to Disney World.', completed: false }
  681. ]);
  682. // Above logs:
  683. // Completed go to Jamaica.
  684. // Removed go to Disneyland.
  685. // Added go to Disney World.
  686. ```
  687. If you need to simply replace the entire content of the collection then `Collection.reset()` can be used:
  688. ```javascript
  689. var TodosCollection = new Backbone.Collection();
  690. // we can listen for reset events
  691. TodosCollection.on("reset", function() {
  692. console.log("Collection reset.");
  693. });
  694. TodosCollection.add([
  695. { title: 'go to Jamaica.', completed: false },
  696. { title: 'go to China.', completed: false },
  697. { title: 'go to Disneyland.', completed: true }
  698. ]);
  699. console.log('Collection size: ' + TodosCollection.length); // Collection size: 3
  700. TodosCollection.reset([
  701. { title: 'go to Cuba.', completed: false }
  702. ]);
  703. // Above logs 'Collection reset.'
  704. console.log('Collection size: ' + TodosCollection.length); // Collection size: 1
  705. ```
  706. Another useful tip is to use `reset` with no arguments to clear out a collection completely. This is handy when dynamically loading a new page of results where you want to blank out the current page of results.
  707. ```javascript
  708. myCollection.reset();
  709. ```
  710. Note that using `Collection.reset()` doesn't fire any `add` or `remove` events. A `reset` event is fired instead as shown in the previous example. The reason you might want to use this is to perform super-optimized rendering in extreme cases where individual events are too expensive.
  711. Also note that listening to a [reset](http://backbonejs.org/#Collection-reset) event, the list of previous models is available in `options.previousModels`, for convenience.
  712. ```javascript
  713. var todo = new Backbone.Model();
  714. var todos = new Backbone.Collection([todo])
  715. .on('reset', function(todos, options) {
  716. console.log(options.previousModels);
  717. console.log([todo]);
  718. console.log(options.previousModels[0] === todo); // true
  719. });
  720. todos.reset([]);
  721. ```
  722. The `set()` method available for Collections can also be used for "smart" updating of sets of models. This method attempts to perform smart updating of a collection using a specified list of models. When a model in this list isn't present in the collection, it is added. If it's present, its attributes will be merged. Models which are present in the collection but not in the list are removed.
  723. ```javascript
  724. // Define a model of type 'Beatle' with a 'job' attribute
  725. var Beatle = Backbone.Model.extend({
  726. defaults: {
  727. job: 'musician'
  728. }
  729. });
  730. // Create models for each member of the Beatles
  731. var john = new Beatle({ firstName: 'John', lastName: 'Lennon'});
  732. var paul = new Beatle({ firstName: 'Paul', lastName: 'McCartney'});
  733. var george = new Beatle({ firstName: 'George', lastName: 'Harrison'});
  734. var ringo = new Beatle({ firstName: 'Ringo', lastName: 'Starr'});
  735. // Create a collection using our models
  736. var theBeatles = new Backbone.Collection([john, paul, george, ringo]);
  737. // Create a separate model for Pete Best
  738. var pete = new Beatle({ firstName: 'Pete', lastName: 'Best'});
  739. // Update the collection
  740. theBeatles.set([john, paul, george, pete]);
  741. // Fires a `remove` event for 'Ringo', and an `add` event for 'Pete'.
  742. // Updates any of John, Paul and Georges's attributes that may have
  743. // changed over the years.
  744. ```
  745. #### Underscore utility functions
  746. Backbone takes full advantage of its hard dependency on Underscore by making many of its utilities directly available on collections:
  747. **`forEach`: iterate over collections**
  748. ```javascript
  749. var todos = new Backbone.Collection();
  750. todos.add([
  751. { title: 'go to Belgium.', completed: false },
  752. { title: 'go to China.', completed: false },
  753. { title: 'go to Austria.', completed: true }
  754. ]);
  755. // iterate over models in the collection
  756. todos.forEach(function(model){
  757. console.log(model.get('title'));
  758. });
  759. // Above logs:
  760. // go to Belgium.
  761. // go to China.
  762. // go to Austria.
  763. ```
  764. **`sortBy()`: sort a collection on a specific attribute**
  765. ```javascript
  766. // sort collection
  767. var sortedByAlphabet = todos.sortBy(function (todo) {
  768. return todo.get("title").toLowerCase();
  769. });
  770. console.log("- Now sorted: ");
  771. sortedByAlphabet.forEach(function(model){
  772. console.log(model.get('title'));
  773. });
  774. // Above logs:
  775. // - Now sorted:
  776. // go to Austria.
  777. // go to Belgium.
  778. // go to China.
  779. ```
  780. **`map()`: iterate through a collection, mapping each value through a transformation function**
  781. ```javascript
  782. var count = 1;
  783. console.log(todos.map(function(model){
  784. return count++ + ". " + model.get('title');
  785. }));
  786. // Above logs:
  787. //1. go to Belgium.
  788. //2. go to China.
  789. //3. go to Austria.
  790. ```
  791. **`min()`/`max()`: retrieve item with the min or max value of an attribute**
  792. ```javascript
  793. todos.max(function(model){
  794. return model.id;
  795. }).id;
  796. todos.min(function(model){
  797. return model.id;
  798. }).id;
  799. ```
  800. **`pluck()`: extract a specific attribute**
  801. ```javascript
  802. var captions = todos.pluck('caption');
  803. // returns list of captions
  804. ```
  805. **`filter()`: filter a collection**
  806. *Filter by an array of model IDs*
  807. ```javascript
  808. var Todos = Backbone.Collection.extend({
  809. model: Todo,
  810. filterById: function(ids){
  811. return this.models.filter(
  812. function(c) {
  813. return _.contains(ids, c.id);
  814. })
  815. }
  816. });
  817. ```
  818. **`indexOf()`: return the index of a particular item within a collection**
  819. ```javascript
  820. var people = new Backbone.Collection;
  821. people.comparator = function(a, b) {
  822. return a.get('name') < b.get('name') ? -1 : 1;
  823. };
  824. var tom = new Backbone.Model({name: 'Tom'});
  825. var rob = new Backbone.Model({name: 'Rob'});
  826. var tim = new Backbone.Model({name: 'Tim'});
  827. people.add(tom);
  828. people.add(rob);
  829. people.add(tim);
  830. console.log(people.indexOf(rob) === 0); // true
  831. console.log(people.indexOf(tim) === 1); // true
  832. console.log(people.indexOf(tom) === 2); // true
  833. ```
  834. **`any()`: confirm if any of the values in a collection pass an iterator truth test**
  835. ```javascript
  836. todos.any(function(model){
  837. return model.id === 100;
  838. });
  839. // or
  840. todos.some(function(model){
  841. return model.id === 100;
  842. });
  843. ```
  844. **`size()`: return the size of a collection**
  845. ```javascript
  846. todos.size();
  847. // equivalent to
  848. todos.length;
  849. ```
  850. **`isEmpty()`: determine whether a collection is empty**
  851. ```javascript
  852. var isEmpty = todos.isEmpty();
  853. ```
  854. **`groupBy()`: group a collection into groups of like items**
  855. ```javascript
  856. var todos = new Backbone.Collection();
  857. todos.add([
  858. { title: 'go to Belgium.', completed: false },
  859. { title: 'go to China.', completed: false },
  860. { title: 'go to Austria.', completed: true }
  861. ]);
  862. // create groups of completed and incomplete models
  863. var byCompleted = todos.groupBy('completed');
  864. var completed = new Backbone.Collection(byCompleted[true]);
  865. console.log(completed.pluck('title'));
  866. // logs: ["go to Austria."]
  867. ```
  868. In addition, several of the Underscore operations on objects are available as methods on Models.
  869. **`pick()`: extract a set of attributes from a model**
  870. ```javascript
  871. var Todo = Backbone.Model.extend({
  872. defaults: {
  873. title: '',
  874. completed: false
  875. }
  876. });
  877. var todo = new Todo({title: 'go to Austria.'});
  878. console.log(todo.pick('title'));
  879. // logs {title: "go to Austria"}
  880. ```
  881. **`omit()`: extract all attributes from a model except those listed**
  882. ```javascript
  883. var todo = new Todo({title: 'go to Austria.'});
  884. console.log(todo.omit('title'));
  885. // logs {completed: false}
  886. ```
  887. **`keys()` and `values()`: get lists of attribute names and values**
  888. ```javascript
  889. var todo = new Todo({title: 'go to Austria.'});
  890. console.log(todo.keys());
  891. // logs: ["title", "completed"]
  892. console.log(todo.values());
  893. //logs: ["go to Austria.", false]
  894. ```
  895. **`pairs()`: get list of attributes as [key, value] pairs**
  896. ```javascript
  897. var todo = new Todo({title: 'go to Austria.'});
  898. var pairs = todo.pairs();
  899. console.log(pairs[0]);
  900. // logs: ["title", "go to Austria."]
  901. console.log(pairs[1]);
  902. // logs: ["completed", false]
  903. ```
  904. **`invert()`: create object in which the values are keys and the attributes are values**
  905. ```javascript
  906. var todo = new Todo({title: 'go to Austria.'});
  907. console.log(todo.invert());
  908. // logs: {'go to Austria.': 'title', 'false': 'completed'}
  909. ```
  910. The complete list of what Underscore can do can be found in its official [documentation](http://documentcloud.github.com/underscore/).
  911. #### Chainable API
  912. Speaking of utility methods, another bit of sugar in Backbone is its support for Underscores `chain()` method. Chaining is a common idiom in object-oriented languages; a chain is a sequence of method calls on the same object that are performed in a single statement. While Backbone makes Underscore's array manipulation operations available as methods of Collection objects, they cannot be directly chained since they return arrays rather than the original Collection.
  913. Fortunately, the inclusion of Underscore's `chain()` method enables you to chain calls to these methods on Collections.
  914. The `chain()` method returns an object that has all of the Underscore array operations attached as methods which return that object. The chain ends with a call to the `value()` method which simply returns the resulting array value. In case you havent seen it before, the chainable API looks like this:
  915. ```javascript
  916. var collection = new Backbone.Collection([
  917. { name: 'Tim', age: 5 },
  918. { name: 'Ida', age: 26 },
  919. { name: 'Rob', age: 55 }
  920. ]);
  921. var filteredNames = collection.chain() // start chain, returns wrapper around collection's models
  922. .filter(function(item) { return item.get('age') > 10; }) // returns wrapped array excluding Tim
  923. .map(function(item) { return item.get('name'); }) // returns wrapped array containing remaining names
  924. .value(); // terminates the chain and returns the resulting array
  925. console.log(filteredNames); // logs: ['Ida', 'Rob']
  926. ```
  927. Some of the Backbone-specific methods do return `this`, which means they can be chained as well:
  928. ```javascript
  929. var collection = new Backbone.Collection();
  930. collection
  931. .add({ name: 'John', age: 23 })
  932. .add({ name: 'Harry', age: 33 })
  933. .add({ name: 'Steve', age: 41 });
  934. var names = collection.pluck('name');
  935. console.log(names); // logs: ['John', 'Harry', 'Steve']
  936. ```
  937. ## RESTful Persistence
  938. Thus far, all of our example data has been created in the browser. For most single page applications, the models are derived from a data store residing on a server. This is an area in which Backbone dramatically simplifies the code you need to write to perform RESTful synchronization with a server through a simple API on its models and collections.
  939. **Fetching models from the server**
  940. `Collections.fetch()` retrieves a set of models from the server in the form of a JSON array by sending an HTTP GET request to the URL specified by the collection's `url` property (which may be a function). When this data is received, a `set()` will be executed to update the collection.
  941. ```javascript
  942. var Todo = Backbone.Model.extend({
  943. defaults: {
  944. title: '',
  945. completed: false
  946. }
  947. });
  948. var TodosCollection = Backbone.Collection.extend({
  949. model: Todo,
  950. url: '/todos'
  951. });
  952. var todos = new TodosCollection();
  953. todos.fetch(); // sends HTTP GET to /todos
  954. ```
  955. **Saving models to the server**
  956. While Backbone can retrieve an entire collection of models from the server at once, updates to models are performed individually using the model's `save()` method. When `save()` is called on a model that was fetched from the server, it constructs a URL by appending the model's id to the collection's URL and sends an HTTP PUT to the server. If the model is a new instance that was created in the browser (i.e., it doesn't have an id) then an HTTP POST is sent to the collection's URL. `Collections.create()` can be used to create a new model, add it to the collection, and send it to the server in a single method call.
  957. ```javascript
  958. var Todo = Backbone.Model.extend({
  959. defaults: {
  960. title: '',
  961. completed: false
  962. }
  963. });
  964. var TodosCollection = Backbone.Collection.extend({
  965. model: Todo,
  966. url: '/todos'
  967. });
  968. var todos = new TodosCollection();
  969. todos.fetch();
  970. var todo2 = todos.get(2);
  971. todo2.set('title', 'go fishing');
  972. todo2.save(); // sends HTTP PUT to /todos/2
  973. todos.create({title: 'Try out code samples'}); // sends HTTP POST to /todos and adds to collection
  974. ```
  975. As mentioned earlier, a model's `validate()` method is called automatically by `save()` and will trigger an `invalid` event on the model if validation fails.
  976. **Deleting models from the server**
  977. A model can be removed from the containing collection and the server by calling its `destroy()` method. Unlike `Collection.remove()` which only removes a model from a collection, `Model.destroy()` will also send an HTTP DELETE to the collection's URL.
  978. ```javascript
  979. var Todo = Backbone.Model.extend({
  980. defaults: {
  981. title: '',
  982. completed: false
  983. }
  984. });
  985. var TodosCollection = Backbone.Collection.extend({
  986. model: Todo,
  987. url: '/todos'
  988. });
  989. var todos = new TodosCollection();
  990. todos.fetch();
  991. var todo2 = todos.get(2);
  992. todo2.destroy(); // sends HTTP DELETE to /todos/2 and removes from collection
  993. ```
  994. Calling `destroy` on a Model will return `false` if the model `isNew`:
  995. ```javascript
  996. var todo = new Backbone.Model();
  997. console.log(todo.destroy());
  998. // false
  999. ```
  1000. **Options**
  1001. Each RESTful API method accepts a variety of options. Most importantly, all methods accept success and error callbacks which can be used to customize the handling of server responses.
  1002. Specifying the `{patch: true}` option to `Model.save()` will cause it to use HTTP PATCH to send only the changed attributes (i.e partial updates) to the server instead of the entire model i.e `model.save(attrs, {patch: true})`:
  1003. ```javascript
  1004. // Save partial using PATCH
  1005. model.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
  1006. model.save();
  1007. model.save({b: 2, d: 4}, {patch: true});
  1008. console.log(this.syncArgs.method);
  1009. // 'patch'
  1010. ```
  1011. Similarly, passing the `{reset: true}` option to `Collection.fetch()` will result in the collection being updated using `reset()` rather than `set()`.
  1012. See the Backbone.js documentation for full descriptions of the supported options.
  1013. ## Events
  1014. Events are a basic inversion of control. Instead of having one function call another by name, the second function is registered as a handler to be called when a specific event occurs.
  1015. The part of your application that has to know how to call the other part of your app has been inverted. This is the core thing that makes it possible for your business logic to not have to know about how your user interface works and is the most powerful thing about the Backbone Events system.
  1016. Mastering events is one of the quickest ways to become more productive with Backbone, so let's take a closer look at Backbone's event model.
  1017. `Backbone.Events` is mixed into the other Backbone "classes", including:
  1018. * Backbone
  1019. * Backbone.Model
  1020. * Backbone.Collection
  1021. * Backbone.Router
  1022. * Backbone.History
  1023. * Backbone.View
  1024. Note that `Backbone.Events` is mixed into the `Backbone` object

Large files files are truncated, but you can click here to view the full file