PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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. Since `Backbone` is globally visible, it can be used as a simple event bus:
  1025. ```javascript
  1026. Backbone.on('event', function() {console.log('Handled Backbone event');});
  1027. Backbone.trigger('event'); // logs: Handled Backbone event
  1028. ```
  1029. #### on(), off(), and trigger()
  1030. `Backbone.Events` can give any object the ability to bind and trigger custom events. We can mix this module into any object easily and there isn't a requirement for events to be declared before being bound to a callback handler.
  1031. Example:
  1032. ```javascript
  1033. var ourObject = {};
  1034. // Mixin
  1035. _.extend(ourObject, Backbone.Events);
  1036. // Add a custom event
  1037. ourObject.on('dance', function(msg){
  1038. console.log('We triggered ' + msg);
  1039. });
  1040. // Trigger the custom event
  1041. ourObject.trigger('dance', 'our event');
  1042. ```
  1043. If you're familiar with jQuery custom events or the concept of Publish/Subscribe, `Backbone.Events` provides a system that is very similar with `on` being analogous to `subscribe` and `trigger` being similar to `publish`.
  1044. `on` binds a callback function to an object, as we've done with `dance` in the above example. The callback is invoked whenever the event is triggered.
  1045. The official Backbone.js documentation recommends namespacing event names using colons if you end up using quite a few of these on your page. e.g.:
  1046. ```javascript
  1047. var ourObject = {};
  1048. // Mixin
  1049. _.extend(ourObject, Backbone.Events);
  1050. function dancing (msg) { console.log("We started " + msg); }
  1051. // Add namespaced custom events
  1052. ourObject.on("dance:tap", dancing);
  1053. ourObject.on("dance:break", dancing);
  1054. // Trigger the custom events
  1055. ourObject.trigger("dance:tap", "tap dancing. Yeah!");
  1056. ourObject.trigger("dance:break", "break dancing. Yeah!");
  1057. // This one triggers nothing as no listener listens for it
  1058. ourObject.trigger("dance", "break dancing. Yeah!");
  1059. ```
  1060. A special `all` event is made available in case you would like notifications for every event that occurs on the object (e.g., if you would like to screen events in a single location). The `all` event can be used as follows:
  1061. ```javascript
  1062. var ourObject = {};
  1063. // Mixin
  1064. _.extend(ourObject, Backbone.Events);
  1065. function dancing (msg) { console.log("We started " + msg); }
  1066. ourObject.on("all", function(eventName){
  1067. console.log("The name of the event passed was " + eventName);
  1068. });
  1069. // This time each event will be caught with a catch 'all' event listener
  1070. ourObject.trigger("dance:tap", "tap dancing. Yeah!");
  1071. ourObject.trigger("dance:break", "break dancing. Yeah!");
  1072. ourObject.trigger("dance", "break dancing. Yeah!");
  1073. ```
  1074. `off` removes callback functions that were previously bound to an object. Going back to our Publish/Subscribe comparison, think of it as an `unsubscribe` for custom events.
  1075. To remove the `dance` event we previously bound to `ourObject`, we would simply do:
  1076. ```javascript
  1077. var ourObject = {};
  1078. // Mixin
  1079. _.extend(ourObject, Backbone.Events);
  1080. function dancing (msg) { console.log("We " + msg); }
  1081. // Add namespaced custom events
  1082. ourObject.on("dance:tap", dancing);
  1083. ourObject.on("dance:break", dancing);
  1084. // Trigger the custom events. Each will be caught and acted upon.
  1085. ourObject.trigger("dance:tap", "started tap dancing. Yeah!");
  1086. ourObject.trigger("dance:break", "started break dancing. Yeah!");
  1087. // Removes event bound to the object
  1088. ourObject.off("dance:tap");
  1089. // Trigger the custom events again, but one is logged.
  1090. ourObject.trigger("dance:tap", "stopped tap dancing."); // won't be logged as it's not listened for
  1091. ourObject.trigger("dance:break", "break dancing. Yeah!");
  1092. ```
  1093. To remove all callbacks for the event we pass an event name (e.g., `move`) to the `off()` method on the object the event is bound to. If we wish to remove a specific callback, we can pass that callback as the second parameter:
  1094. ```javascript
  1095. var ourObject = {};
  1096. // Mixin
  1097. _.extend(ourObject, Backbone.Events);
  1098. function dancing (msg) { console.log("We are dancing. " + msg); }
  1099. function jumping (msg) { console.log("We are jumping. " + msg); }
  1100. // Add two listeners to the same event
  1101. ourObject.on("move", dancing);
  1102. ourObject.on("move", jumping);
  1103. // Trigger the events. Both listeners are called.
  1104. ourObject.trigger("move", "Yeah!");
  1105. // Removes specified listener
  1106. ourObject.off("move", dancing);
  1107. // Trigger the events again. One listener left.
  1108. ourObject.trigger("move", "Yeah, jump, jump!");
  1109. ```
  1110. Finally, as we have seen in our previous examples, `trigger` triggers a callback for a specified event (or a space-separated list of events). e.g.:
  1111. ```javascript
  1112. var ourObject = {};
  1113. // Mixin
  1114. _.extend(ourObject, Backbone.Events);
  1115. function doAction (msg) { console.log("We are " + msg); }
  1116. // Add event listeners
  1117. ourObject.on("dance", doAction);
  1118. ourObject.on("jump", doAction);
  1119. ourObject.on("skip", doAction);
  1120. // Single event
  1121. ourObject.trigger("dance", 'just dancing.');
  1122. // Multiple events
  1123. ourObject.trigger("dance jump skip", 'very tired from so much action.');
  1124. ```
  1125. `trigger` can pass multiple arguments to the callback function:
  1126. ```javascript
  1127. var ourObject = {};
  1128. // Mixin
  1129. _.extend(ourObject, Backbone.Events);
  1130. function doAction (action, duration) {
  1131. console.log("We are " + action + ' for ' + duration );
  1132. }
  1133. // Add event listeners
  1134. ourObject.on("dance", doAction);
  1135. ourObject.on("jump", doAction);
  1136. ourObject.on("skip", doAction);
  1137. // Passing multiple arguments to single event
  1138. ourObject.trigger("dance", 'dancing', "5 minutes");
  1139. // Passing multiple arguments to multiple events
  1140. ourObject.trigger("dance jump skip", 'on fire', "15 minutes");
  1141. ```
  1142. #### listenTo() and stopListening()
  1143. While `on()` and `off()` add callbacks directly to an observed object, `listenTo()` tells an object to listen for events on another object, allowing the listener to keep track of the events for which it is listening. `stopListening()` can subsequently be called on the listener to tell it to stop listening for events:
  1144. ```javascript
  1145. var a = _.extend({}, Backbone.Events);
  1146. var b = _.extend({}, Backbone.Events);
  1147. var c = _.extend({}, Backbone.Events);
  1148. // add listeners to A for events on B and C
  1149. a.listenTo(b, 'anything', function(event){ console.log("anything happened"); });
  1150. a.listenTo(c, 'everything', function(event){ console.log("everything happened"); });
  1151. // trigger an event
  1152. b.trigger('anything'); // logs: anything happened
  1153. // stop listening
  1154. a.stopListening();
  1155. // A does not receive these events
  1156. b.trigger('anything');
  1157. c.trigger('everything');
  1158. ```
  1159. `stopListening()` can also be used to selectively stop listening based on the event, model, or callback handler.
  1160. If you use `on` and `off` and remove views and their corresponding models at the same time, there are generally no problems. But a problem arises when you remove a view that had registered to be notified about events on a model, but you don't remove the model or call `off` to remove the view's event handler. Since the model has a reference to the view's callback function, the JavaScript garbage collector cannot remove the view from memory. This is called a "ghost view" and is a form of memory leak which is common since the models generally tend to outlive the corresponding views during an application's lifecycle. For details on the topic and a solution, check this [excellent article](http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/) by Derick Bailey.
  1161. Practically, every `on` called on an object also requires an `off` to be called in order for the garbage collector to do its job. `listenTo()` changes that, allowing Views to bind to Model notifications and unbind from all of them with just one call - `stopListening()`.
  1162. The default implementation of `View.remove()` makes a call to `stopListening()`, ensuring that any listeners bound using `listenTo()` are unbound before the view is destroyed.
  1163. ```javascript
  1164. var view = new Backbone.View();
  1165. var b = _.extend({}, Backbone.Events);
  1166. view.listenTo(b, 'all', function(){ console.log(true); });
  1167. b.trigger('anything'); // logs: true
  1168. view.listenTo(b, 'all', function(){ console.log(false); });
  1169. view.remove(); // stopListening() implicitly called
  1170. b.trigger('anything'); // does not log anything
  1171. ```
  1172. #### Events and Views
  1173. Within a View, there are two types of events you can listen for: DOM events and events triggered using the Event API. It is important to understand the differences in how views bind to these events and the context in which their callbacks are invoked.
  1174. DOM events can be bound to using the View's `events` property or using `jQuery.on()`. Within callbacks bound using the `events` property, `this` refers to the View object; whereas any callbacks bound directly using jQuery will have `this` set to the handling DOM element by jQuery. All DOM event callbacks are passed an `event` object by jQuery. See `delegateEvents()` in the Backbone documentation for additional details.
  1175. Event API events are bound as described in this section. If the event is bound using `on()` on the observed object, a context parameter can be passed as the third argument. If the event is bound using `listenTo()` then within the callback `this` refers to the listener. The arguments passed to Event API callbacks depends on the type of event. See the Catalog of Events in the Backbone documentation for details.
  1176. The following example illustrates these differences:
  1177. ```html
  1178. <div id="todo">
  1179. <input type='checkbox' />
  1180. </div>
  1181. ```
  1182. ```javascript
  1183. var View = Backbone.View.extend({
  1184. el: '#todo',
  1185. // bind to DOM event using events property
  1186. events: {
  1187. 'click [type="checkbox"]': 'clicked',
  1188. },
  1189. initialize: function () {
  1190. // bind to DOM event using jQuery
  1191. this.$el.click(this.jqueryClicked);
  1192. // bind to API event
  1193. this.on('apiEvent', this.callback);
  1194. },
  1195. // 'this' is view
  1196. clicked: function(event) {
  1197. console.log("events handler for " + this.el.outerHTML);
  1198. this.trigger('apiEvent', event.type);
  1199. },
  1200. // 'this' is handling DOM element
  1201. jqueryClicked: function(event) {
  1202. console.log("jQuery handler for " + this.outerHTML);
  1203. },
  1204. callback: function(eventType) {
  1205. console.log("event type was " + eventType);
  1206. }
  1207. });
  1208. var view = new View();
  1209. ```
  1210. ## Routers
  1211. In Backbone, routers provide a way for you to connect URLs (either hash fragments, or
  1212. real) to parts of your application. Any piece of your application that you want
  1213. to be bookmarkable, shareable, and back-button-able, needs a URL.
  1214. Some examples of routes using the hash mark may be seen below:
  1215. ```javascript
  1216. http://example.com/#about
  1217. http://example.com/#search/seasonal-horns/page2
  1218. ```
  1219. An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that route. This relationship is defined as follows:
  1220. ```javascript
  1221. 'route' : 'mappedFunction'
  1222. ```
  1223. Let's define our first router by extending `Backbone.Router`. For the purposes of this guide, we're going to continue pretending we're creating a complex todo application (something like a personal organizer/planner) that requires a complex TodoRouter.
  1224. Note the inline comments in the code example below as they continue our lesson on routers.
  1225. ```javascript
  1226. var TodoRouter = Backbone.Router.extend({
  1227. /* define the route and function maps for this router */
  1228. routes: {
  1229. "about" : "showAbout",
  1230. /* Sample usage: http://example.com/#about */
  1231. "todo/:id" : "getTodo",
  1232. /* This is an example of using a ":param" variable which allows us to match
  1233. any of the components between two URL slashes */
  1234. /* Sample usage: http://example.com/#todo/5 */
  1235. "search/:query" : "searchTodos",
  1236. /* We can also define multiple routes that are bound to the same map function,
  1237. in this case searchTodos(). Note below how we're optionally passing in a
  1238. reference to a page number if one is supplied */
  1239. /* Sample usage: http://example.com/#search/job */
  1240. "search/:query/p:page" : "searchTodos",
  1241. /* As we can see, URLs may contain as many ":param"s as we wish */
  1242. /* Sample usage: http://example.com/#search/job/p1 */
  1243. "todos/:id/download/*documentPath" : "downloadDocument",
  1244. /* This is an example of using a *splat. Splats are able to match any number of
  1245. URL components and can be combined with ":param"s*/
  1246. /* Sample usage: http://example.com/#todos/5/download/files/Meeting_schedule.doc */
  1247. /* If you wish to use splats for anything beyond default routing, it's probably a good
  1248. idea to leave them at the end of a URL otherwise you may need to apply regular
  1249. expression parsing on your fragment */
  1250. "*other" : "defaultRoute",
  1251. /* This is a default route that also uses a *splat. Consider the
  1252. default route a wildcard for URLs that are either not matched or where
  1253. the user has incorrectly typed in a route path manually */
  1254. /* Sample usage: http://example.com/# <anything> */
  1255. "optional(/:item)": "optionalItem",
  1256. "named/optional/(y:z)": "namedOptionalItem"
  1257. /* Router URLs also support optional parts via parentheses, without having
  1258. to use a regex. */
  1259. },
  1260. showAbout: function(){
  1261. },
  1262. getTodo: function(id){
  1263. /*
  1264. Note that the id matched in the above route will be passed to this function
  1265. */
  1266. console.log("You are trying to reach todo " + id);
  1267. },
  1268. searchTodos: function(query, page){
  1269. var page_number = page || 1;
  1270. console.log("Page number: " + page_number + " of the results for todos containing the word: " + query);
  1271. },
  1272. downloadDocument: function(id, path){
  1273. },
  1274. defaultRoute: function(other){
  1275. console.log('Invalid. You attempted to reach:' + other);
  1276. }
  1277. });
  1278. /* Now that we have a router setup, we need to instantiate it */
  1279. var myTodoRouter = new TodoRouter();
  1280. ```
  1281. Backbone offers an opt-in for HTML5 pushState support via `window.history.pushState`. This permits you to define routes such as http://backbonejs.org/just/an/example. This will be supported with automatic degradation when a user's browser doesn't support pushState. Note that it is vastly preferred if you're capable of also supporting pushState on the server side, although it is a little more difficult to implement.
  1282. **Is there a limit to the number of routers I should be using?**
  1283. Andrew de Andrade has pointed out that DocumentCloud, the creators of Backbone, usually only use a single router in most of their applications. You're very likely to not require more than one or two routers in your own projects; the majority of your application routing can be kept organized in a single router without it getting unwieldy.
  1284. #### Backbone.history
  1285. Next, we need to initialize `Backbone.history` as it handles `hashchange` events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.
  1286. The `Backbone.history.start()` method will simply tell Backbone that it's okay to begin monitoring all `hashchange` events as follows:
  1287. ```javascript
  1288. var TodoRouter = Backbone.Router.extend({
  1289. /* define the route and function maps for this router */
  1290. routes: {
  1291. "about" : "showAbout",
  1292. "search/:query" : "searchTodos",
  1293. "search/:query/p:page" : "searchTodos"
  1294. },
  1295. showAbout: function(){},
  1296. searchTodos: function(query, page){
  1297. var page_number = page || 1;
  1298. console.log("Page number: " + page_number + " of the results for todos containing the word: " + query);
  1299. }
  1300. });
  1301. var myTodoRouter = new TodoRouter();
  1302. Backbone.history.start();
  1303. // Go to and check console:
  1304. // http://localhost/#search/job/p3 logs: Page number: 3 of the results for todos containing the word: job
  1305. // http://localhost/#search/job logs: Page number: 1 of the results for todos containing the word: job
  1306. // etc.
  1307. ```
  1308. Note: To run the last example, you'll need to create a local development environment and test project, which we will cover later on in the book.
  1309. If you would like to update the URL to reflect the application state at a particular point, you can use the router's `.navigate()` method. By default, it simply updates your URL fragment without triggering the `hashchange` event:
  1310. ```javascript
  1311. // Let's imagine we would like a specific fragment (edit) once a user opens a single todo
  1312. var TodoRouter = Backbone.Router.extend({
  1313. routes: {
  1314. "todo/:id": "viewTodo",
  1315. "todo/:id/edit": "editTodo"
  1316. // ... other routes
  1317. },
  1318. viewTodo: function(id){
  1319. console.log("View todo requested.");
  1320. this.navigate("todo/" + id + '/edit'); // updates the fragment for us, but doesn't trigger the route
  1321. },
  1322. editTodo: function(id) {
  1323. console.log("Edit todo opened.");
  1324. }
  1325. });
  1326. var myTodoRouter = new TodoRouter();
  1327. Backbone.history.start();
  1328. // Go to: http://localhost/#todo/4
  1329. //
  1330. // URL is updated to: http://localhost/#todo/4/edit
  1331. // but editTodo() function is not invoked even though location we end up is mapped to it.
  1332. //
  1333. // logs: View todo requested.
  1334. ```
  1335. It is also possible for `Router.navigate()` to trigger the route along with updating the URL fragment by passing the `trigger:true` option.
  1336. Note: This usage is discouraged. The recommended usage is the one described above which creates a bookmarkable URL when your application transitions to a specific state.
  1337. ```javascript
  1338. var TodoRouter = Backbone.Router.extend({
  1339. routes: {
  1340. "todo/:id": "viewTodo",
  1341. "todo/:id/edit": "editTodo"
  1342. // ... other routes
  1343. },
  1344. viewTodo: function(id){
  1345. console.log("View todo requested.");
  1346. this.navigate("todo/" + id + '/edit', {trigger: true}); // updates the fragment and triggers the route as well
  1347. },
  1348. editTodo: function(id) {
  1349. console.log("Edit todo opened.");
  1350. }
  1351. });
  1352. var myTodoRouter = new TodoRouter();
  1353. Backbone.history.start();
  1354. // Go to: http://localhost/#todo/4
  1355. //
  1356. // URL is updated to: http://localhost/#todo/4/edit
  1357. // and this time editTodo() function is invoked.
  1358. //
  1359. // logs:
  1360. // View todo requested.
  1361. // Edit todo opened.
  1362. ```
  1363. A "route" event is also triggered on the router in addition to being fired on Backbone.history.
  1364. ```javascript
  1365. Backbone.history.on('route', onRoute);
  1366. // Trigger 'route' event on router instance.
  1367. router.on('route', function(name, args) {
  1368. console.log(name === 'routeEvent');
  1369. });
  1370. location.replace('http://example.com#route-event/x');
  1371. Backbone.history.checkUrl();
  1372. ```
  1373. ## Backbones Sync API
  1374. We previously discussed how Backbone supports RESTful persistence via its `fetch()` and `create()` methods on Collections and `save()`, and `destroy()` methods on Models. Now we are going to take a closer look at Backbone's sync method which underlies these operations.
  1375. The Backbone.sync method is an integral part of Backbone.js. It assumes a jQuery-like `$.ajax()` method, so HTTP parameters are organized based on jQuerys API. Since some legacy servers may not support JSON-formatted requests and HTTP PUT and DELETE operations, Backbone can be configured to emulate these capabilities using the two configuration variables shown below with their default values:
  1376. ```javascript
  1377. Backbone.emulateHTTP = false; // set to true if server cannot handle HTTP PUT or HTTP DELETE
  1378. Backbone.emulateJSON = false; // set to true if server cannot handle application/json requests
  1379. ```
  1380. The inline Backbone.emulateHTTP option should be set to true if extended HTTP methods are not supported by the server. The Backbone.emulateJSON option should be set to true if the server does not understand the MIME type for JSON.
  1381. ```javascript
  1382. // Create a new library collection
  1383. var Library = Backbone.Collection.extend({
  1384. url : function() { return '/library'; }
  1385. });
  1386. // Define attributes for our model
  1387. var attrs = {
  1388. title : "The Tempest",
  1389. author : "Bill Shakespeare",
  1390. length : 123
  1391. };
  1392. // Create a new Library instance
  1393. var library = new Library;
  1394. // Create a new instance of a model within our collection
  1395. library.create(attrs, {wait: false});
  1396. // Update with just emulateHTTP
  1397. library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}, {
  1398. emulateHTTP: true
  1399. });
  1400. // Check the ajaxSettings being used for our request
  1401. console.log(this.ajaxSettings.url === '/library/2-the-tempest'); // true
  1402. console.log(this.ajaxSettings.type === 'POST'); // true
  1403. console.log(this.ajaxSettings.contentType === 'application/json'); // true
  1404. // Parse the data for the request to confirm it is as expected
  1405. var data = JSON.parse(this.ajaxSettings.data);
  1406. console.log(data.id === '2-the-tempest'); // true
  1407. console.log(data.author === 'Tim Shakespeare'); // true
  1408. console.log(data.length === 123); // true
  1409. ```
  1410. Similarly, we could just update using `emulateJSON`:
  1411. ```javascript
  1412. library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}, {
  1413. emulateJSON: true
  1414. });
  1415. console.log(this.ajaxSettings.url === '/library/2-the-tempest'); // true
  1416. console.log(this.ajaxSettings.type === 'PUT'); // true
  1417. console.log(this.ajaxSettings.contentType ==='application/x-www-form-urlencoded'); // true
  1418. var data = JSON.parse(this.ajaxSettings.data.model);
  1419. console.log(data.id === '2-the-tempest');
  1420. console.log(data.author ==='Tim Shakespeare');
  1421. console.log(data.length === 123);
  1422. ```
  1423. `Backbone.sync` is called every time Backbone tries to read, save, or delete models. It uses jQuery or Zepto's `$.ajax()` implementations to make these RESTful requests, however this can be overridden as per your needs.
  1424. **Overriding Backbone.sync**
  1425. The `sync` function may be overridden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.
  1426. Since all persistence is handled by the Backbone.sync function, an alternative persistence layer can be used by simply overriding Backbone.sync with a function that has the same signature:
  1427. ```javascript
  1428. Backbone.sync = function(method, model, options) {
  1429. };
  1430. ```
  1431. The methodMap below is used by the standard sync implementation to map the method parameter to an HTTP operation and illustrates the type of action required by each method argument:
  1432. ```javascript
  1433. var methodMap = {
  1434. 'create': 'POST',
  1435. 'update': 'PUT',
  1436. 'patch': 'PATCH',
  1437. 'delete': 'DELETE',
  1438. 'read': 'GET'
  1439. };
  1440. ```
  1441. If we wanted to replace the standard `sync` implementation with one that simply logged the calls to sync, we could do this:
  1442. ```javascript
  1443. var id_counter = 1;
  1444. Backbone.sync = function(method, model) {
  1445. console.log("I've been passed " + method + " with " + JSON.stringify(model));
  1446. if(method === 'create'){ model.set('id', id_counter++); }
  1447. };
  1448. ```
  1449. Note that we assign a unique id to any created models.
  1450. The Backbone.sync method is intended to be overridden to support other persistence backends. The built-in method is tailored to a certain breed of RESTful JSON APIs - Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT in the same way.
  1451. The sync method is called with three parameters:
  1452. * method: One of create, update, patch, delete, or read
  1453. * model: The Backbone model object
  1454. * options: May include success and error methods
  1455. Implementing a new sync method can use the following pattern:
  1456. ```javascript
  1457. Backbone.sync = function(method, model, options) {
  1458. function success(result) {
  1459. // Handle successful results from MyAPI
  1460. if (options.success) {
  1461. options.success(result);
  1462. }
  1463. }
  1464. function error(result) {
  1465. // Handle error results from MyAPI
  1466. if (options.error) {
  1467. options.error(result);
  1468. }
  1469. }
  1470. options || (options = {});
  1471. switch (method) {
  1472. case 'create':
  1473. return MyAPI.create(model, success, error);
  1474. case 'update':
  1475. return MyAPI.update(model, success, error);
  1476. case 'patch':
  1477. return MyAPI.patch(model, success, error);
  1478. case 'delete':
  1479. return MyAPI.destroy(model, success, error);
  1480. case 'read':
  1481. if (model.cid) {
  1482. return MyAPI.find(model, success, error);
  1483. } else {
  1484. return MyAPI.findAll(model, success, error);
  1485. }
  1486. }
  1487. };
  1488. ```
  1489. This pattern delegates API calls to a new object (MyAPI), which could be a Backbone-style class that supports events. This can be safely tested separately, and potentially used with libraries other than Backbone.
  1490. There are quite a few sync implementations out there. The following examples are all available on GitHub:
  1491. * Backbone localStorage: persists to the browser's local storage
  1492. * Backbone offline: supports working offline
  1493. * Backbone Redis: uses Redis key-value store
  1494. * backbone-parse: integrates Backbone with Parse.com
  1495. * backbone-websql: stores data to WebSQL
  1496. * Backbone Caching Sync: uses local storage as cache for other sync implementations
  1497. ## Dependencies
  1498. The official Backbone.js [documentation](http://backbonejs.org/) states:
  1499. >Backbone's only hard dependency is either Underscore.js ( >= 1.4.3) or Lo-Dash. For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto.
  1500. What this translates to is that if you require working with anything beyond models, you will need to include a DOM manipulation library such as jQuery or Zepto. Underscore is primarily used for its utility methods (which Backbone relies upon heavily) and json2.js for legacy browser JSON support if Backbone.sync is used.
  1501. ## Summary
  1502. In this chapter we have introduced you to the components you will be using to build applications with Backbone: Models, Views, Collections, and Routers. We've also explored the Events mix-in that Backbone uses to enhance all components with publish-subscribe capabilities and seen how it can be used with arbitrary objects. Finally, we saw how Backbone leverages the Underscore.js and jQuery/Zepto APIs to add rich manipulation and persistence features to Backbone Collections and Models.
  1503. Backbone has many operations and options beyond those we have covered here and is always evolving, so be sure to visit the official [documentation](http://backbonejs.org/) for more details and the latest features. In the next chapter you will start to get your hands dirty as we walk you through the implementation of your first Backbone application.