Debian Codegraph @

index.html

raw ◀ ▶
2 Debian patches touch this file
1 <!DOCTYPE HTML>
2 <html>
3 <head>
4 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
5 <meta http-equiv="X-UA-Compatible" content="chrome=1" />
6 <meta name="viewport" content="width=device-width">
7 <link rel="canonical" href="http://backbonejs.org" />
8 <title>Backbone.js</title>
9 <style>
10 body {
11 font-size: 14px;
12 line-height: 22px;
13 font-family: Helvetica Neue, Helvetica, Arial;
14 background: #f4f4f4 url(docs/images/background.png);
15 }
16 .interface {
17 font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
18 }
19 div#sidebar {
20 background: #fff;
21 position: fixed;
22 z-index: 10;
23 top: 0; left: 0; bottom: 0;
24 width: 200px;
25 overflow-y: auto;
26 overflow-x: hidden;
27 -webkit-overflow-scrolling: touch;
28 padding: 15px 0 30px 30px;
29 border-right: 1px solid #bbb;
30 box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
31 }
32 a.toc_title, a.toc_title:visited {
33 display: block;
34 color: black;
35 font-weight: bold;
36 margin-top: 15px;
37 }
38 a.toc_title:hover {
39 text-decoration: underline;
40 }
41 #sidebar .version {
42 font-size: 10px;
43 font-weight: normal;
44 }
45 ul.toc_section {
46 font-size: 11px;
47 line-height: 14px;
48 margin: 5px 0 0 0;
49 padding-left: 0px;
50 list-style-type: none;
51 font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif;
52 }
53 .toc_section li {
54 cursor: pointer;
55 margin: 0 0 3px 0;
56 }
57 .toc_section li a {
58 text-decoration: none;
59 color: black;
60 }
61 .toc_section li a:hover {
62 text-decoration: underline;
63 }
64 input#function_filter {
65 width: 80%;
66 }
67 div.container {
68 position: relative;
69 width: 550px;
70 margin: 40px 0 50px 260px;
71 }
72 img#logo {
73 width: 450px;
74 height: 80px;
75 }
76 div.run {
77 position: absolute;
78 right: 15px;
79 width: 26px; height: 18px;
80 background: url('docs/images/arrows.png') no-repeat -26px 0;
81 }
82 div.run:active {
83 background-position: -51px 0;
84 }
85 p, div.container ul {
86 margin: 25px 0;
87 width: 550px;
88 }
89 p.warning {
90 font-size: 12px;
91 line-height: 18px;
92 font-style: italic;
93 }
94 div.container ul {
95 list-style: circle;
96 padding-left: 15px;
97 font-size: 13px;
98 line-height: 18px;
99 }
100 div.container ul li {
101 margin-bottom: 10px;
102 }
103 div.container ul.small {
104 font-size: 12px;
105 }
106 a, a:visited {
107 color: #444;
108 }
109 a:active, a:hover {
110 color: #000;
111 }
112 a.punch {
113 display: inline-block;
114 background: #4162a8;
115 border-top: 1px solid #38538c;
116 border-right: 1px solid #1f2d4d;
117 border-bottom: 1px solid #151e33;
118 border-left: 1px solid #1f2d4d;
119 -webkit-border-radius: 4px;
120 -moz-border-radius: 4px;
121 -ms-border-radius: 4px;
122 -o-border-radius: 4px;
123 border-radius: 4px;
124 -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
125 -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
126 -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
127 -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
128 box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
129 color: #fff;
130 font: bold 14px "helvetica neue", helvetica, arial, sans-serif;
131 line-height: 1;
132 margin-bottom: 15px;
133 padding: 8px 0 10px 0;
134 text-align: center;
135 text-shadow: 0px -1px 1px #1e2d4d;
136 text-decoration: none;
137 width: 225px;
138 -webkit-background-clip: padding-box; }
139 a.punch:hover {
140 -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
141 -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
142 -ms-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
143 -o-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
144 box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
145 cursor: pointer; }
146 a.punch:active {
147 -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
148 -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
149 -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
150 -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
151 box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
152 margin-top: 5px; margin-bottom: 10px; }
153 a img {
154 border: 0;
155 }
156 h1, h2, h3, h4, h5, h6 {
157 padding-top: 20px;
158 }
159 h2 {
160 font-size: 22px;
161 }
162 b.header {
163 font-size: 18px;
164 line-height: 35px;
165 }
166 span.alias {
167 font-size: 14px;
168 font-style: italic;
169 margin-left: 20px;
170 }
171 table {
172 margin: 15px 0 0; padding: 0;
173 }
174 tr, td {
175 margin: 0; padding: 0;
176 }
177 td {
178 padding: 0px 15px 5px 0;
179 }
180 table .rule {
181 height: 1px;
182 background: #ccc;
183 margin: 5px 0;
184 }
185 code, pre, tt {
186 font-family: Monaco, Consolas, "Lucida Console", monospace;
187 font-size: 12px;
188 line-height: 18px;
189 font-style: normal;
190 }
191 tt {
192 padding: 0px 3px;
193 background: #fff;
194 border: 1px solid #ddd;
195 zoom: 1;
196 }
197 code {
198 margin-left: 20px;
199 }
200 pre {
201 font-size: 12px;
202 padding: 2px 0 2px 15px;
203 border: 4px solid #bbb; border-top: 0; border-bottom: 0;
204 margin: 0px 0 25px;
205 }
206 img.example_image {
207 margin: 0px auto;
208 }
209 img.example_retina {
210 margin: 20px;
211 box-shadow: 0 8px 15px rgba(0,0,0,0.4);
212 }
213 @media only screen and (-webkit-max-device-pixel-ratio: 1) and (max-width: 600px),
214 only screen and (max--moz-device-pixel-ratio: 1) and (max-width: 600px) {
215 div#sidebar {
216 display: none;
217 }
218 img#logo {
219 max-width: 450px;
220 width: 100%;
221 height: auto;
222 }
223 div.container {
224 width: auto;
225 margin-left: 15px;
226 margin-right: 15px;
227 }
228 p, div.container ul {
229 width: auto;
230 }
231 }
232 @media only screen and (-webkit-min-device-pixel-ratio: 1.5) and (max-width: 640px),
233 only screen and (-o-min-device-pixel-ratio: 3/2) and (max-width: 640px),
234 only screen and (min-device-pixel-ratio: 1.5) and (max-width: 640px) {
235 img {
236 max-width: 100%;
237 height: auto;
238 }
239 div#sidebar {
240 -webkit-overflow-scrolling: initial;
241 position: relative;
242 width: 90%;
243 height: 120px;
244 left: 0;
245 top: -7px;
246 padding: 10px 0 10px 30px;
247 border: 0;
248 }
249 img#logo {
250 width: auto;
251 height: auto;
252 }
253 div.container {
254 margin: 0;
255 width: 100%;
256 }
257 p, div.container ul {
258 max-width: 98%;
259 overflow-x: scroll;
260 }
261 table {
262 position: relative;
263 }
264 tr:first-child td {
265 padding-bottom: 25px;
266 }
267 td.text {
268 line-height: 12px;
269 padding: 0;
270 position: absolute;
271 left: 0;
272 top: 48px;
273 }
274 tr:last-child td.text {
275 top: 122px;
276 }
277 pre {
278 overflow: scroll;
279 }
280 }
281 img.figure {
282 width: 100%;
283 }
284 div.columns {
285 display: table;
286 table-layout: fixed;
287 width: 100%;
288 }
289 div.columns ul {
290 margin: 10px 0;
291 }
292 div.col-50 {
293 display: table-cell;
294 width: 50%;
295 }
296 </style>
297 </head>
298 <body>
299
300 <div id="sidebar" class="interface">
301
302 <a class="toc_title" href="#">
303 Backbone.js <span class="version">(1.4.1)</span>
304 </a>
305 <ul class="toc_section">
306 <li>&raquo; <a href="http://github.com/jashkenas/backbone">GitHub Repository</a></li>
307 <li>&raquo; <a href="docs/backbone.html">Annotated Source</a></li>
308 </ul>
309
310 <input id="function_filter" placeholder="Filter" type="text" autofocus />
311
312 <div class="searchable_section">
313 <a class="toc_title" href="#Getting-started">
314 Getting Started
315 </a>
316 <ul class="toc_section">
317 <li data-name="Introduction">- <a href="#Getting-started">Introduction</a></li>
318 <li data-name="Models and Views">– <a href="#Model-View-separation">Models and Views</a></li>
319 <li data-name="Collections">– <a href="#Model-Collections">Collections</a></li>
320 <li data-name="API Integration">– <a href="#API-integration">API Integration</a></li>
321 <li data-name="Rendering">– <a href="#View-rendering">Rendering</a></li>
322 <li data-name="Routing">– <a href="#Routing">Routing</a></li>
323 </ul>
324 </div>
325
326 <div class="searchable_section">
327 <a class="toc_title" href="#Events">
328 Events
329 </a>
330 <ul class="toc_section">
331 <li data-name="on">– <a href="#Events-on">on</a></li>
332 <li data-name="off">– <a href="#Events-off">off</a></li>
333 <li data-name="trigger">– <a href="#Events-trigger">trigger</a></li>
334 <li data-name="once">– <a href="#Events-once">once</a></li>
335 <li data-name="listenTo">– <a href="#Events-listenTo">listenTo</a></li>
336 <li data-name="stopListening">– <a href="#Events-stopListening">stopListening</a></li>
337 <li data-name="listenToOnce">– <a href="#Events-listenToOnce">listenToOnce</a></li>
338 <li data-name="Catalog of Built-in Events">- <a href="#Events-catalog"><b>Catalog of Built-in Events</b></a></li>
339 </ul>
340 </div>
341
342 <div class="searchable_section">
343 <a class="toc_title" href="#Model">
344 Model
345 </a>
346 <ul class="toc_section">
347 <li data-name="extend">– <a href="#Model-extend">extend</a></li>
348 <li data-name="preinitialize">– <a href="#Model-preinitialize">preinitialize</a></li>
349 <li data-name="constructor / initialize">– <a href="#Model-constructor">constructor / initialize</a></li>
350 <li data-name="get">– <a href="#Model-get">get</a></li>
351 <li data-name="set">– <a href="#Model-set">set</a></li>
352 <li data-name="escape">– <a href="#Model-escape">escape</a></li>
353 <li data-name="has">– <a href="#Model-has">has</a></li>
354 <li data-name="unset">– <a href="#Model-unset">unset</a></li>
355 <li data-name="clear">– <a href="#Model-clear">clear</a></li>
356 <li data-name="id">– <a href="#Model-id">id</a></li>
357 <li data-name="idAttribute">– <a href="#Model-idAttribute">idAttribute</a></li>
358 <li data-name="cid">– <a href="#Model-cid">cid</a></li>
359 <li data-name="attributes">– <a href="#Model-attributes">attributes</a></li>
360 <li data-name="changed">– <a href="#Model-changed">changed</a></li>
361 <li data-name="defaults">– <a href="#Model-defaults">defaults</a></li>
362 <li data-name="toJSON">– <a href="#Model-toJSON">toJSON</a></li>
363 <li data-name="sync">– <a href="#Model-sync">sync</a></li>
364 <li data-name="fetch">– <a href="#Model-fetch">fetch</a></li>
365 <li data-name="save">– <a href="#Model-save">save</a></li>
366 <li data-name="destroy">– <a href="#Model-destroy">destroy</a></li>
367 <li data-name="Underscore Methods">– <a href="#Model-Underscore-Methods"><b>Underscore Methods (9)</b></a></li>
368 <li data-name="validate">– <a href="#Model-validate">validate</a></li>
369 <li data-name="validationError">– <a href="#Model-validationError">validationError</a></li>
370 <li data-name="isValid">– <a href="#Model-isValid">isValid</a></li>
371 <li data-name="url">– <a href="#Model-url">url</a></li>
372 <li data-name="urlRoot">– <a href="#Model-urlRoot">urlRoot</a></li>
373 <li data-name="parse">– <a href="#Model-parse">parse</a></li>
374 <li data-name="clone">– <a href="#Model-clone">clone</a></li>
375 <li data-name="isNew">– <a href="#Model-isNew">isNew</a></li>
376 <li data-name="hasChanged">– <a href="#Model-hasChanged">hasChanged</a></li>
377 <li data-name="changedAttributes">– <a href="#Model-changedAttributes">changedAttributes</a></li>
378 <li data-name="previous">– <a href="#Model-previous">previous</a></li>
379 <li data-name="previousAttributes">– <a href="#Model-previousAttributes">previousAttributes</a></li>
380 </ul>
381 </div>
382
383 <div class="searchable_section">
384 <a class="toc_title" href="#Collection">
385 Collection
386 </a>
387 <ul class="toc_section">
388 <li data-name="extend">– <a href="#Collection-extend">extend</a></li>
389 <li data-name="model">– <a href="#Collection-model">model</a></li>
390 <li data-name="modelId">– <a href="#Collection-modelId">modelId</a></li>
391 <li data-name="preinitialize" data-name="preinitialize">– <a href="#Collection-preinitialize">preinitialize</a></li>
392 <li data-name="constructor / initialize" data-name="constructor / initialize">– <a href="#Collection-constructor">constructor / initialize</a></li>
393 <li data-name="models">– <a href="#Collection-models">models</a></li>
394 <li data-name="toJSON">– <a href="#Collection-toJSON">toJSON</a></li>
395 <li data-name="sync">– <a href="#Collection-sync">sync</a></li>
396 <li data-name="Underscore Methods">– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (46)</b></a></li>
397 <li data-name="add">– <a href="#Collection-add">add</a></li>
398 <li data-name="remove">– <a href="#Collection-remove">remove</a></li>
399 <li data-name="reset">– <a href="#Collection-reset">reset</a></li>
400 <li data-name="set">– <a href="#Collection-set">set</a></li>
401 <li data-name="get">– <a href="#Collection-get">get</a></li>
402 <li data-name="at">– <a href="#Collection-at">at</a></li>
403 <li data-name="push">– <a href="#Collection-push">push</a></li>
404 <li data-name="pop">– <a href="#Collection-pop">pop</a></li>
405 <li data-name="unshift">– <a href="#Collection-unshift">unshift</a></li>
406 <li data-name="shift">– <a href="#Collection-shift">shift</a></li>
407 <li data-name="slice">– <a href="#Collection-slice">slice</a></li>
408 <li data-name="length">– <a href="#Collection-length">length</a></li>
409 <li data-name="comparator">– <a href="#Collection-comparator">comparator</a></li>
410 <li data-name="sort">– <a href="#Collection-sort">sort</a></li>
411 <li data-name="pluck">– <a href="#Collection-pluck">pluck</a></li>
412 <li data-name="where">– <a href="#Collection-where">where</a></li>
413 <li data-name="findWhere">– <a href="#Collection-findWhere">findWhere</a></li>
414 <li data-name="url">– <a href="#Collection-url">url</a></li>
415 <li data-name="parse">– <a href="#Collection-parse">parse</a></li>
416 <li data-name="clone">– <a href="#Collection-clone">clone</a></li>
417 <li data-name="fetch">– <a href="#Collection-fetch">fetch</a></li>
418 <li data-name="create">– <a href="#Collection-create">create</a></li>
419 <li data-name="sync">– <a href="#Collection-mixin">mixin</a></li>
420 </ul>
421 </div>
422
423 <div class="searchable_section">
424 <a class="toc_title" href="#Router">
425 Router
426 </a>
427 <ul class="toc_section">
428 <li data-name="extend">– <a href="#Router-extend">extend</a></li>
429 <li data-name="routes">– <a href="#Router-routes">routes</a></li>
430 <li data-name="preinitialize">– <a href="#Router-preinitialize">preinitialize</a></li>
431 <li data-name="constructor / initialize">– <a href="#Router-constructor">constructor / initialize</a></li>
432 <li data-name="route">– <a href="#Router-route">route</a></li>
433 <li data-name="navigate">– <a href="#Router-navigate">navigate</a></li>
434 <li data-name="execute">– <a href="#Router-execute">execute</a></li>
435 </ul>
436 </div>
437
438 <div class="searchable_section">
439 <a class="toc_title" href="#History">
440 History
441 </a>
442 <ul class="toc_section">
443 <li data-name="start">– <a href="#History-start">start</a></li>
444 </ul>
445 </div>
446
447 <div class="searchable_section">
448 <a class="toc_title" href="#Sync">
449 Sync
450 </a>
451 <ul class="toc_section">
452 <li data-name="Backbone.sync">– <a href="#Sync">Backbone.sync</a></li>
453 <li data-name="Backbone.ajax">– <a href="#Sync-ajax">Backbone.ajax</a></li>
454 <li data-name="Backbone.emulateHTTP">– <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
455 <li data-name="Backbone.emulateJSON">– <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
456 </ul>
457 </div>
458
459 <div class="searchable_section">
460 <a class="toc_title" href="#View">
461 View
462 </a>
463 <ul class="toc_section">
464 <li data-name="extend">– <a href="#View-extend">extend</a></li>
465 <li data-name="preinitialize">– <a href="#View-preinitialize">preinitialize</a></li>
466 <li data-name="constructor / initialize">– <a href="#View-constructor">constructor / initialize</a></li>
467 <li data-name="el">– <a href="#View-el">el</a></li>
468 <li data-name="$el">– <a href="#View-$el">$el</a></li>
469 <li data-name="setElement">– <a href="#View-setElement">setElement</a></li>
470 <li data-name="attributes">– <a href="#View-attributes">attributes</a></li>
471 <li data-name="$ (jQuery)">– <a href="#View-dollar">$ (jQuery)</a></li>
472 <li data-name="template">– <a href="#View-template">template</a></li>
473 <li data-name="render">– <a href="#View-render">render</a></li>
474 <li data-name="remove">– <a href="#View-remove">remove</a></li>
475 <li data-name="events">– <a href="#View-events">events</a></li>
476 <li data-name="delegateEvents">– <a href="#View-delegateEvents">delegateEvents</a></li>
477 <li data-name="undelegateEvents">– <a href="#View-undelegateEvents">undelegateEvents</a></li>
478 </ul>
479 </div>
480
481 <div class="searchable_section">
482 <a class="toc_title" href="#Utility">
483 Utility
484 </a>
485 <ul class="toc_section">
486 <li data-name="Backbone.noConflict">– <a href="#Utility-Backbone-noConflict">Backbone.noConflict</a></li>
487 <li data-name="Backbone.$">– <a href="#Utility-Backbone-$">Backbone.$</a></li>
488 </ul>
489 </div>
490
491 <div class="searchable_section">
492 <a class="toc_title" href="#faq">
493 F.A.Q.
494 </a>
495 <ul class="toc_section">
496 <li data-name="Why Backbone?">– <a href="#FAQ-why-backbone">Why Backbone?</a></li>
497 <li data-name="More Than One Way To Do It">– <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
498 <li data-name="Nested Models and Collections">– <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
499 <li data-name="Loading Bootstrapped Models">– <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
500 <li data-name="Extending Backbone">– <a href="#FAQ-extending">Extending Backbone</a></li>
501 <li data-name="Traditional MVC">– <a href="#FAQ-mvc">Traditional MVC</a></li>
502 <li data-name="Binding this">– <a href="#FAQ-this">Binding "this"</a></li>
503 <li data-name="Working with Rails">– <a href="#FAQ-rails">Working with Rails</a></li>
504 </ul>
505 </div>
506
507 <div class="searchable_section">
508 <a class="toc_title" href="#examples">
509 Examples
510 </a>
511 <ul class="toc_section">
512 <li data-name="Todos">– <a href="#examples-todos">Todos</a></li>
513 <li data-name="DocumentCloud">– <a href="#examples-documentcloud">DocumentCloud</a></li>
514 <li data-name="USA Today">– <a href="#examples-usa-today">USA Today</a></li>
515 <li data-name="Rdio">– <a href="#examples-rdio">Rdio</a></li>
516 <li data-name="Hulu">– <a href="#examples-hulu">Hulu</a></li>
517 <li data-name="Quartz">– <a href="#examples-quartz">Quartz</a></li>
518 <li data-name="Earth">– <a href="#examples-earth">Earth</a></li>
519 <li data-name="Vox">– <a href="#examples-vox">Vox</a></li>
520 <li data-name="Gawker Media">– <a href="#examples-gawker">Gawker Media</a></li>
521 <li data-name="Flow">– <a href="#examples-flow">Flow</a></li>
522 <li data-name="Gilt Groupe">– <a href="#examples-gilt">Gilt Groupe</a></li>
523 <li data-name="Enigma">– <a href="#examples-enigma">Enigma</a></li>
524 <li data-name="NewsBlur">– <a href="#examples-newsblur">NewsBlur</a></li>
525 <li data-name="WordPress.com">– <a href="#examples-wordpress">WordPress.com</a></li>
526 <li data-name="Foursquare">– <a href="#examples-foursquare">Foursquare</a></li>
527 <li data-name="Bitbucket">– <a href="#examples-bitbucket">Bitbucket</a></li>
528 <li data-name="Disqus">– <a href="#examples-disqus">Disqus</a></li>
529 <li data-name="Delicious">– <a href="#examples-delicious">Delicious</a></li>
530 <li data-name="Khan Academy">– <a href="#examples-khan-academy">Khan Academy</a></li>
531 <li data-name="IRCCloud">– <a href="#examples-irccloud">IRCCloud</a></li>
532 <li data-name="Pitchfork">– <a href="#examples-pitchfork">Pitchfork</a></li>
533 <li data-name="Spin">– <a href="#examples-spin">Spin</a></li>
534 <li data-name="ZocDoc">– <a href="#examples-zocdoc">ZocDoc</a></li>
535 <li data-name="Walmart Mobile">– <a href="#examples-walmart">Walmart Mobile</a></li>
536 <li data-name="Groupon Now!">– <a href="#examples-groupon">Groupon Now!</a></li>
537 <li data-name="Basecamp">– <a href="#examples-basecamp">Basecamp</a></li>
538 <li data-name="Slavery Footprint">– <a href="#examples-slavery-footprint">Slavery Footprint</a></li>
539 <li data-name="Stripe">– <a href="#examples-stripe">Stripe</a></li>
540 <li data-name="Airbnb">– <a href="#examples-airbnb">Airbnb</a></li>
541 <li data-name="SoundCloud Mobile">– <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
542 <li data-name="Art.sy">- <a href="#examples-artsy">Art.sy</a></li>
543 <li data-name="Pandora">– <a href="#examples-pandora">Pandora</a></li>
544 <li data-name="Inkling">– <a href="#examples-inkling">Inkling</a></li>
545 <li data-name="Code School">– <a href="#examples-code-school">Code School</a></li>
546 <li data-name="CloudApp">– <a href="#examples-cloudapp">CloudApp</a></li>
547 <li data-name="SeatGeek">– <a href="#examples-seatgeek">SeatGeek</a></li>
548 <li data-name="Easel">– <a href="#examples-easel">Easel</a></li>
549 <li data-name="Jolicloud">- <a href="#examples-jolicloud">Jolicloud</a></li>
550 <li data-name="Salon.io">– <a href="#examples-salon">Salon.io</a></li>
551 <li data-name="TileMill">– <a href="#examples-tilemill">TileMill</a></li>
552 <li data-name="Blossom">– <a href="#examples-blossom">Blossom</a></li>
553 <li data-name="Trello">– <a href="#examples-trello">Trello</a></li>
554 <li data-name="Tzigla">– <a href="#examples-tzigla">Tzigla</a></li>
555 </ul>
556 </div>
557
558 <div class="searchable_section">
559 <a class="toc_title" href="#changelog">
560 Change Log
561 </a>
562 </div>
563
564 </div>
565
566 <div class="container">
567
568 <p>
569 <img id="logo" src="docs/images/backbone.png" alt="Backbone.js" />
570 </p>
571
572 <p>
573 Backbone.js gives structure to web applications
574 by providing <b>models</b> with key-value binding and custom events,
575 <b>collections</b> with a rich API of enumerable functions,
576 <b>views</b> with declarative event handling, and connects it all to your
577 existing API over a RESTful JSON interface.
578 </p>
579
580 <p>
581 The project is <a href="http://github.com/jashkenas/backbone/">hosted on GitHub</a>,
582 and the <a href="docs/backbone.html">annotated source code</a> is available,
583 as well as an online <a href="test/">test suite</a>,
584 an <a href="examples/todos/index.html">example application</a>,
585 a <a href="https://github.com/jashkenas/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>
586 and a <a href="#examples">long list of real-world projects</a> that use Backbone.
587 Backbone is available for use under the <a href="http://github.com/jashkenas/backbone/blob/master/LICENSE">MIT software license</a>.
588 </p>
589
590 <p>
591 You can report bugs and discuss features on the
592 <a href="http://github.com/jashkenas/backbone/issues">GitHub issues page</a>,
593 or add pages to the <a href="https://github.com/jashkenas/backbone/wiki">wiki</a>.
594 </p>
595
596 <p>
597 <i>
598 Backbone is an open-source component of
599 <a href="http://documentcloud.org/">DocumentCloud</a>.
600 </i>
601 </p>
602
603 <h2 id="downloads">
604 Downloads &amp; Dependencies
605 <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
606 </h2>
607
608 <table>
609 <tr>
610 <td><a class="punch" href="backbone.js">Development Version (1.4.1)</a></td>
611 <td class="text"><i>72kb, Full source, tons of comments</i></td>
612 </tr>
613 <tr>
614 <td><a class="punch" href="backbone-min.js">Production Version (1.4.1)</a></td>
615 <td class="text" style="line-height: 16px;">
616 <i>7.9kb, Packed and gzipped</i><br />
617 <small>(<a href="backbone-min.map">Source Map</a>)</small>
618 </td>
619 </tr>
620 <tr>
621 <td><a class="punch" href="https://raw.github.com/jashkenas/backbone/master/backbone.js">Edge Version (master)</a></td>
622 <td>
623 <i>Unreleased, use at your own risk</i>
624 </td>
625 </tr>
626 </table>
627
628 <p>
629 Backbone's only hard dependency is
630 <a href="http://underscorejs.org/">Underscore.js</a> <small>( >= 1.8.3)</small>.
631 For RESTful persistence and DOM manipulation with <a href="#View">Backbone.View</a>,
632 include <b><a href="https://jquery.com/">jQuery</a></b> ( >= 1.11.0).
633 <i>(Mimics of the Underscore and jQuery APIs, such as
634 <a href="https://lodash.com/">Lodash</a> and
635 <a href="http://zeptojs.com/">Zepto</a>, will
636 also tend to work, with varying degrees of compatibility.)</i>
637 </p>
638 <h2 id="Getting-started">Getting Started</h2>
639
640 <p>
641 When working on a web application that involves a lot of JavaScript, one
642 of the first things you learn is to stop tying your data to the DOM. It's all
643 too easy to create JavaScript applications that end up as tangled piles of
644 jQuery selectors and callbacks, all trying frantically to keep data in
645 sync between the HTML UI, your JavaScript logic, and the database on your
646 server. For rich client-side applications, a more structured approach
647 is often helpful.
648 </p>
649
650 <p>
651 With Backbone, you represent your data as
652 <a href="#Model">Models</a>, which can be created, validated, destroyed,
653 and saved to the server. Whenever a UI action causes an attribute of
654 a model to change, the model triggers a <i>"change"</i> event; all
655 the <a href="#View">Views</a> that display the model's state can be notified of the
656 change, so that they are able to respond accordingly, re-rendering themselves with
657 the new information. In a finished Backbone app, you don't have to write the glue
658 code that looks into the DOM to find an element with a specific <i>id</i>,
659 and update the HTML manually
660 &mdash; when the model changes, the views simply update themselves.
661 </p>
662
663 <p>
664 Philosophically, Backbone is an attempt to discover the minimal set
665 of data-structuring (models and collections) and user interface (views
666 and URLs) primitives that are generally useful when building web applications with
667 JavaScript. In an ecosystem where overarching, decides-everything-for-you
668 frameworks are commonplace, and many libraries require your site to be
669 reorganized to suit their look, feel, and default behavior — Backbone should
670 continue to be a tool that gives you the <i>freedom</i> to design the full
671 experience of your web application.
672 </p>
673
674 <p>
675 If you're new here, and aren't yet quite sure what Backbone is for, start by
676 browsing the <a href="#examples">list of Backbone-based projects</a>.
677 </p>
678
679 <p>
680 Many of the code examples in this documentation are runnable, because
681 Backbone is included on this page.
682 Click the <i>play</i> button to execute them.
683 </p>
684
685 <h2 id="Model-View-separation">Models and Views</h2>
686
687 <img class="figure" src="docs/images/intro-model-view.svg" alt="Model-View Separation.">
688
689 <p>
690 The single most important thing that Backbone can help you with is keeping
691 your business logic separate from your user interface. When the two are
692 entangled, change is hard; when logic doesn't depend on UI, your
693 interface becomes easier to work with.
694 </p>
695
696 <div class="columns">
697 <div class="col-50">
698 <b>Model</b>
699 <ul>
700 <li>Orchestrates data and business logic.</li>
701 <li>Loads and saves data from the server.</li>
702 <li>Emits events when data changes.</li>
703 </ul>
704 </div>
705 <div class="col-50">
706 <b>View</b>
707 <ul>
708 <li>Listens for changes and renders UI.</li>
709 <li>Handles user input and interactivity.</li>
710 <li>Sends captured input to the model.</li>
711 </ul>
712 </div>
713 </div>
714
715 <p>
716 A <b>Model</b> manages an internal table of data attributes, and
717 triggers <tt>"change"</tt> events when any of its data is modified.
718 Models handle syncing data with a persistence layer — usually a REST API
719 with a backing database. Design your models as the atomic reusable objects
720 containing all of the helpful functions for manipulating their particular
721 bit of data. Models should be able to be passed around throughout your app,
722 and used anywhere that bit of data is needed.
723 </p>
724
725 <p>
726 A <b>View</b> is an atomic chunk of user interface. It often renders the
727 data from a specific model, or number of models &mdash; but views can
728 also be data-less chunks of UI that stand alone.
729 Models should be generally unaware of views. Instead, views listen to
730 the model <tt>"change"</tt> events, and react or re-render themselves
731 appropriately.
732 </p>
733
734 <h2 id="Model-Collections">Collections</h2>
735
736 <img class="figure" src="docs/images/intro-collections.svg" alt="Model Collections.">
737
738 <p>
739 A <b>Collection</b> helps you deal with a group of related models, handling
740 the loading and saving of new models to the server and providing helper
741 functions for performing aggregations or computations against a list of models.
742 Aside from their own events, collections also proxy through all of the
743 events that occur to models within them, allowing you to listen in one place
744 for any change that might happen to any model in the collection.
745 </p>
746
747 <h2 id="API-integration">API Integration</h2>
748
749 <p>
750 Backbone is pre-configured to sync with a RESTful API. Simply create a
751 new Collection with the <tt>url</tt> of your resource endpoint:
752 </p>
753
754 <pre>
755 var Books = Backbone.Collection.extend({
756 url: '/books'
757 });
758 </pre>
759
760 <p>
761 The <b>Collection</b> and <b>Model</b> components together form a direct
762 mapping of REST resources using the following methods:
763 </p>
764
765 <pre>
766 GET /books/ .... collection.fetch();
767 POST /books/ .... collection.create();
768 GET /books/1 ... model.fetch();
769 PUT /books/1 ... model.save();
770 DEL /books/1 ... model.destroy();
771 </pre>
772
773 <p>
774 When fetching raw JSON data from an API, a <b>Collection</b> will
775 automatically populate itself with data formatted as an array, while
776 a <b>Model</b> will automatically populate itself with data formatted
777 as an object:
778 </p>
779
780 <pre>
781 [{"id": 1}] ..... populates a Collection with one model.
782 {"id": 1} ....... populates a Model with one attribute.
783 </pre>
784
785 <p>
786 However, it's fairly common to encounter APIs that return data in a
787 different format than what Backbone expects. For example, consider
788 fetching a <b>Collection</b> from an API that returns the real data
789 array wrapped in metadata:
790 </p>
791
792 <pre>
793 {
794 "page": 1,
795 "limit": 10,
796 "total": 2,
797 "books": [
798 {"id": 1, "title": "Pride and Prejudice"},
799 {"id": 4, "title": "The Great Gatsby"}
800 ]
801 }
802 </pre>
803
804 <p>
805 In the above example data, a <b>Collection</b> should populate using the
806 <tt>"books"</tt> array rather than the root object structure. This
807 difference is easily reconciled using a <tt>parse</tt> method that
808 returns (or transforms) the desired portion of API data:
809 </p>
810
811 <pre>
812 var Books = Backbone.Collection.extend({
813 url: '/books',
814 parse: function(data) {
815 return data.books;
816 }
817 });
818 </pre>
819
820 <h2 id="View-rendering">View Rendering</h2>
821
822 <img class="figure" src="docs/images/intro-views.svg" alt="View rendering.">
823
824 <p>
825 Each <b>View</b> manages the rendering and user interaction within its own
826 DOM element. If you're strict about not allowing views to reach outside
827 of themselves, it helps keep your interface flexible &mdash; allowing
828 views to be rendered in isolation in any place where they might be needed.
829 </p>
830
831 <p>
832 Backbone remains unopinionated about the process used to render <b>View</b>
833 objects and their subviews into UI: you define how your models get translated
834 into HTML (or SVG, or Canvas, or something even more exotic).
835 It could be as prosaic as a simple
836 <a href="http://underscorejs.org/#template">Underscore template</a>, or as fancy as the
837 <a href="http://facebook.github.io/react/docs/tutorial.html">React virtual DOM</a>.
838 Some basic approaches to rendering views can be found
839 in the <a href="https://github.com/jashkenas/backbone/wiki/Backbone%2C-The-Primer">Backbone primer</a>.
840 </p>
841
842 <h2 id="Routing">Routing with URLs</h2>
843
844 <img class="figure" src="docs/images/intro-routing.svg" alt="Routing">
845
846 <p>
847 In rich web applications, we still want to provide linkable,
848 bookmarkable, and shareable URLs to meaningful locations within an app.
849 Use the <b>Router</b> to update the browser URL whenever the user
850 reaches a new "place" in your app that they might want to bookmark or share.
851 Conversely, the <b>Router</b> detects changes to the URL &mdash; say,
852 pressing the "Back" button &mdash; and can tell your application exactly where you
853 are now.
854 </p>
855
856 <h2 id="Events">Backbone.Events</h2>
857
858 <p>
859 <b>Events</b> is a module that can be mixed in to any object, giving the
860 object the ability to bind and trigger custom named events. Events do not
861 have to be declared before they are bound, and may take passed arguments.
862 For example:
863 </p>
864
865 <pre class="runnable">
866 var object = {};
867
868 _.extend(object, Backbone.Events);
869
870 object.on("alert", function(msg) {
871 alert("Triggered " + msg);
872 });
873
874 object.trigger("alert", "an event");
875 </pre>
876
877 <p>
878 For example, to make a handy event dispatcher that can coordinate events
879 among different areas of your application: <tt>var dispatcher = _.clone(Backbone.Events)</tt>
880 </p>
881
882 <p id="Events-on">
883 <b class="header">on</b><code>object.on(event, callback, [context])</code><span class="alias">Alias: bind</span>
884 <br />
885 Bind a <b>callback</b> function to an object. The callback will be invoked
886 whenever the <b>event</b> is fired.
887 If you have a large number of different events on a page, the convention is to use colons to
888 namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>.
889 The event string may also be a space-delimited list of several events...
890 </p>
891
892 <pre>
893 book.on("change:title change:author", ...);
894 </pre>
895
896 <p>
897 Callbacks bound to the special
898 <tt>"all"</tt> event will be triggered when any event occurs, and are passed
899 the name of the event as the first argument. For example, to proxy all events
900 from one object to another:
901 </p>
902
903 <pre>
904 proxy.on("all", function(eventName) {
905 object.trigger(eventName);
906 });
907 </pre>
908
909 <p>
910 All Backbone event methods also support an event map syntax, as an alternative
911 to positional arguments:
912 </p>
913
914 <pre>
915 book.on({
916 "change:author": authorPane.update,
917 "change:title change:subtitle": titleView.update,
918 "destroy": bookView.remove
919 });
920 </pre>
921
922 <p>
923 To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
924 pass the optional last argument: <tt>model.on('change', this.render, this)</tt> or
925 <tt>model.on({change: this.render}, this)</tt>.
926 </p>
927
928 <p id="Events-off">
929 <b class="header">off</b><code>object.off([event], [callback], [context])</code><span class="alias">Alias: unbind</span>
930 <br />
931 Remove a previously-bound <b>callback</b> function from an object. If no
932 <b>context</b> is specified, all of the versions of the callback with
933 different contexts will be removed. If no
934 callback is specified, all callbacks for the <b>event</b> will be
935 removed. If no event is specified, callbacks for <i>all</i> events
936 will be removed.
937 </p>
938
939 <pre>
940 // Removes just the `onChange` callback.
941 object.off("change", onChange);
942
943 // Removes all "change" callbacks.
944 object.off("change");
945
946 // Removes the `onChange` callback for all events.
947 object.off(null, onChange);
948
949 // Removes all callbacks for `context` for all events.
950 object.off(null, null, context);
951
952 // Removes all callbacks on `object`.
953 object.off();
954 </pre>
955
956 <p>
957 Note that calling <tt>model.off()</tt>, for example, will indeed remove <i>all</i> events
958 on the model &mdash; including events that Backbone uses for internal bookkeeping.
959 </p>
960
961 <p id="Events-trigger">
962 <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
963 <br />
964 Trigger callbacks for the given <b>event</b>, or space-delimited list of events.
965 Subsequent arguments to <b>trigger</b> will be passed along to the
966 event callbacks.
967 </p>
968
969 <p id="Events-once">
970 <b class="header">once</b><code>object.once(event, callback, [context])</code>
971 <br />
972 Just like <a href="#Events-on">on</a>, but causes the bound callback to fire
973 only once before being removed. Handy for saying "the next time that X happens, do this".
974 When multiple events are passed in using the space separated syntax, the event will fire once
975 for every event you passed in, not once for a combination of all events
976 </p>
977
978 <p id="Events-listenTo">
979 <b class="header">listenTo</b><code>object.listenTo(other, event, callback)</code>
980 <br />
981 Tell an <b>object</b> to listen to a particular event on an <b>other</b>
982 object. The advantage of using this form, instead of <tt>other.on(event,
983 callback, object)</tt>, is that <b>listenTo</b> allows the <b>object</b>
984 to keep track of the events, and they can be removed all at once later
985 on. The <b>callback</b> will always be called with <b>object</b> as
986 context.
987 </p>
988
989 <pre>
990 view.listenTo(model, 'change', view.render);
991 </pre>
992
993 <p id="Events-stopListening">
994 <b class="header">stopListening</b><code>object.stopListening([other], [event], [callback])</code>
995 <br />
996 Tell an <b>object</b> to stop listening to events. Either call
997 <b>stopListening</b> with no arguments to have the <b>object</b> remove
998 all of its <a href="#Events-listenTo">registered</a> callbacks ... or be more
999 precise by telling it to remove just the events it's listening to on a
1000 specific object, or a specific event, or just a specific callback.
1001 </p>
1002
1003 <pre>
1004 view.stopListening();
1005
1006 view.stopListening(model);
1007 </pre>
1008
1009 <p id="Events-listenToOnce">
1010 <b class="header">listenToOnce</b><code>object.listenToOnce(other, event, callback)</code>
1011 <br />
1012 Just like <a href="#Events-listenTo">listenTo</a>, but causes the bound
1013 callback to fire only once before being removed.
1014 </p>
1015
1016 <p id="Events-catalog">
1017 <b class="header">Catalog of Events</b>
1018 <br />
1019 Here's the complete list of built-in Backbone events, with arguments.
1020 You're also free to trigger your own events on Models, Collections and
1021 Views as you see fit. The <tt>Backbone</tt> object itself mixes in <tt>Events</tt>,
1022 and can be used to emit any global events that your application needs.
1023 </p>
1024
1025 <ul class="small">
1026 <li><b>"add"</b> (model, collection, options) &mdash; when a model is added to a collection.</li>
1027 <li><b>"remove"</b> (model, collection, options) &mdash; when a model is removed from a collection.</li>
1028 <li><b>"update"</b> (collection, options) &mdash; single event triggered after any number of models have been added, removed or changed in a collection.</li>
1029 <li><b>"reset"</b> (collection, options) &mdash; when the collection's entire contents have been <a href="#Collection-reset">reset</a>.</li>
1030 <li><b>"sort"</b> (collection, options) &mdash; when the collection has been re-sorted.</li>
1031 <li><b>"change"</b> (model, options) &mdash; when a model's attributes have changed.</li>
1032 <li><b>"changeId"</b> (model, previousId, options) &mdash; when the model's id has been updated.</li>
1033 <li><b>"change:[attribute]"</b> (model, value, options) &mdash; when a specific attribute has been updated.</li>
1034 <li><b>"destroy"</b> (model, collection, options) &mdash; when a model is <a href="#Model-destroy">destroyed</a>.</li>
1035 <li><b>"request"</b> (model_or_collection, xhr, options) &mdash; when a model or collection has started a request to the server.</li>
1036 <li><b>"sync"</b> (model_or_collection, response, options) &mdash; when a model or collection has been successfully synced with the server.</li>
1037 <li><b>"error"</b> (model_or_collection, xhr, options) &mdash; when a model's or collection's request to the server has failed.</li>
1038 <li><b>"invalid"</b> (model, error, options) &mdash; when a model's <a href="#Model-validate">validation</a> fails on the client.</li>
1039 <li><b>"route:[name]"</b> (params) &mdash; Fired by the router when a specific route is matched.</li>
1040 <li><b>"route"</b> (route, params) &mdash; Fired by the router when <i>any</i> route has been matched.</li>
1041 <li><b>"route"</b> (router, route, params) &mdash; Fired by history when <i>any</i> route has been matched.</li>
1042 <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument followed by all trigger arguments.</li>
1043 </ul>
1044
1045 <p>
1046 Generally speaking, when calling a function that emits an event
1047 (<tt>model.set</tt>, <tt>collection.add</tt>, and so on...),
1048 if you'd like to prevent the event from being triggered, you may pass
1049 <tt>{silent: true}</tt> as an option. Note that this is <i>rarely</i>,
1050 perhaps even never, a good idea. Passing through a specific flag
1051 in the options for your event callback to look at, and choose to ignore,
1052 will usually work out better.
1053 </p>
1054
1055 <h2 id="Model">Backbone.Model</h2>
1056
1057 <p>
1058 <b>Models</b> are the heart of any JavaScript application, containing
1059 the interactive data as well as a large part of the logic surrounding it:
1060 conversions, validations, computed properties, and access control. You
1061 extend <b>Backbone.Model</b> with your domain-specific methods, and
1062 <b>Model</b> provides a basic set of functionality for managing changes.
1063 </p>
1064
1065 <p>
1066 The following is a contrived example, but it demonstrates defining a model
1067 with a custom method, setting an attribute, and firing an event keyed
1068 to changes in that specific attribute.
1069 After running this code once, <tt>sidebar</tt> will be
1070 available in your browser's console, so you can play around with it.
1071 </p>
1072
1073 <pre class="runnable">
1074 var Sidebar = Backbone.Model.extend({
1075 promptColor: function() {
1076 var cssColor = prompt("Please enter a CSS color:");
1077 this.set({color: cssColor});
1078 }
1079 });
1080
1081 window.sidebar = new Sidebar;
1082
1083 sidebar.on('change:color', function(model, color) {
1084 $('#sidebar').css({background: color});
1085 });
1086
1087 sidebar.set({color: 'white'});
1088
1089 sidebar.promptColor();
1090 </pre>
1091
1092 <p id="Model-extend">
1093 <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
1094 <br />
1095 To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
1096 and provide instance <b>properties</b>, as well as optional
1097 <b>classProperties</b> to be attached directly to the constructor function.
1098 </p>
1099
1100 <p>
1101 <b>extend</b> correctly sets up the prototype chain, so subclasses created
1102 with <b>extend</b> can be further extended and subclassed as far as you like.
1103 </p>
1104
1105 <pre>
1106 var Note = Backbone.Model.extend({
1107
1108 initialize: function() { ... },
1109
1110 author: function() { ... },
1111
1112 coordinates: function() { ... },
1113
1114 allowedToEdit: function(account) {
1115 return true;
1116 }
1117
1118 });
1119
1120 var PrivateNote = Note.extend({
1121
1122 allowedToEdit: function(account) {
1123 return account.owns(this);
1124 }
1125
1126 });
1127 </pre>
1128
1129 <p class="warning">
1130 Brief aside on <tt>super</tt>: JavaScript does not provide
1131 a simple way to call super &mdash; the function of the same name defined
1132 higher on the prototype chain. If you override a core function like
1133 <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
1134 parent object's implementation, you'll have to explicitly call it, along these lines:
1135 </p>
1136
1137 <pre>
1138 var Note = Backbone.Model.extend({
1139 set: function(attributes, options) {
1140 Backbone.Model.prototype.set.apply(this, arguments);
1141 ...
1142 }
1143 });
1144 </pre>
1145
1146 <p id="Model-preinitialize">
1147 <b class="header">preinitialize</b><code>new Model([attributes], [options])</code>
1148 <br />
1149 For use with models as ES classes. If you define a <b>preinitialize</b>
1150 method, it will be invoked when the Model is first created, before any
1151 instantiation logic is run for the Model.
1152 </p>
1153
1154 <pre>
1155 class Country extends Backbone.Model {
1156 preinitialize({countryCode}) {
1157 this.name = COUNTRY_NAMES[countryCode];
1158 }
1159
1160 initialize() { ... }
1161 }
1162 </pre>
1163
1164 <p id="Model-constructor">
1165 <b class="header">constructor / initialize</b><code>new Model([attributes], [options])</code>
1166 <br />
1167 When creating an instance of a model, you can pass in the initial values
1168 of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
1169 model. If you define an <b>initialize</b> function, it will be invoked when
1170 the model is created.
1171 </p>
1172
1173 <pre>
1174 new Book({
1175 title: "One Thousand and One Nights",
1176 author: "Scheherazade"
1177 });
1178 </pre>
1179
1180 <p>
1181 In rare cases, if you're looking to get fancy,
1182 you may want to override <b>constructor</b>, which allows
1183 you to replace the actual constructor function for your model.
1184 </p>
1185
1186 <pre>
1187 var Library = Backbone.Model.extend({
1188 constructor: function() {
1189 this.books = new Books();
1190 Backbone.Model.apply(this, arguments);
1191 },
1192 parse: function(data, options) {
1193 this.books.reset(data.books);
1194 return data.library;
1195 }
1196 });
1197 </pre>
1198
1199 <p>
1200 If you pass a <tt>{collection: ...}</tt> as the <b>options</b>, the model
1201 gains a <tt>collection</tt> property that will be used to indicate which
1202 collection the model belongs to, and is used to help compute the model's
1203 <a href="#Model-url">url</a>. The <tt>model.collection</tt> property is
1204 normally created automatically when you first add a model to a collection.
1205 Note that the reverse is not true, as passing this option to the constructor
1206 will not automatically add the model to the collection. Useful, sometimes.
1207 </p>
1208
1209 <p>
1210 If <tt>{parse: true}</tt> is passed as an <b>option</b>, the <b>attributes</b>
1211 will first be converted by <a href="#Model-parse">parse</a> before being
1212 <a href="#Model-set">set</a> on the model.
1213 </p>
1214
1215 <p id="Model-get">
1216 <b class="header">get</b><code>model.get(attribute)</code>
1217 <br />
1218 Get the current value of an attribute from the model. For example:
1219 <tt>note.get("title")</tt>
1220 </p>
1221
1222 <p id="Model-set">
1223 <b class="header">set</b><code>model.set(attributes, [options])</code>
1224 <br />
1225 Set a hash of attributes (one or many) on the model. If any of the attributes
1226 change the model's state, a <tt>"change"</tt> event will be triggered on the model.
1227 Change events for specific attributes are also triggered, and you can bind
1228 to those as well, for example: <tt>change:title</tt>, and <tt>change:content</tt>.
1229 You may also pass individual keys and values.
1230 </p>
1231
1232 <pre>
1233 note.set({title: "March 20", content: "In his eyes she eclipses..."});
1234
1235 book.set("title", "A Scandal in Bohemia");
1236 </pre>
1237
1238 <p id="Model-escape">
1239 <b class="header">escape</b><code>model.escape(attribute)</code>
1240 <br />
1241 Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
1242 of a model's attribute. If you're interpolating data from the model into
1243 HTML, using <b>escape</b> to retrieve attributes will prevent
1244 <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
1245 </p>
1246
1247 <pre class="runnable">
1248 var hacker = new Backbone.Model({
1249 name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
1250 });
1251
1252 alert(hacker.escape('name'));
1253 </pre>
1254
1255 <p id="Model-has">
1256 <b class="header">has</b><code>model.has(attribute)</code>
1257 <br />
1258 Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
1259 value.
1260 </p>
1261
1262 <pre>
1263 if (note.has("title")) {
1264 ...
1265 }
1266 </pre>
1267
1268 <p id="Model-unset">
1269 <b class="header">unset</b><code>model.unset(attribute, [options])</code>
1270 <br />
1271 Remove an attribute by deleting it from the internal attributes hash.
1272 Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
1273 </p>
1274
1275 <p id="Model-clear">
1276 <b class="header">clear</b><code>model.clear([options])</code>
1277 <br />
1278 Removes all attributes from the model, including the <tt>id</tt> attribute. Fires a <tt>"change"</tt> event unless
1279 <tt>silent</tt> is passed as an option.
1280 </p>
1281
1282 <p id="Model-id">
1283 <b class="header">id</b><code>model.id</code>
1284 <br />
1285 A special property of models, the <b>id</b> is an arbitrary string
1286 (integer id or UUID). If you set the <b>id</b> in the
1287 attributes hash, it will be copied onto the model as a direct property.
1288 <code>model.id</code> should not be manipulated directly,
1289 it should be modified only via <code>model.set('id', …)</code>.
1290 Models can be retrieved by id from collections, and the id is used to generate
1291 model URLs by default.
1292 </p>
1293
1294 <p id="Model-idAttribute">
1295 <b class="header">idAttribute</b><code>model.idAttribute</code>
1296 <br />
1297 A model's unique identifier is stored under the <tt>id</tt> attribute.
1298 If you're directly communicating with a backend (CouchDB, MongoDB) that uses
1299 a different unique key, you may set a Model's <tt>idAttribute</tt> to
1300 transparently map from that key to <tt>id</tt>.
1301
1302 <pre class="runnable">
1303 var Meal = Backbone.Model.extend({
1304 idAttribute: "_id"
1305 });
1306
1307 var cake = new Meal({ _id: 1, name: "Cake" });
1308 alert("Cake id: " + cake.id);
1309 </pre>
1310 </p>
1311
1312 <p id="Model-cid">
1313 <b class="header">cid</b><code>model.cid</code>
1314 <br />
1315 A special property of models, the <b>cid</b> or client id is a unique identifier
1316 automatically assigned to all models when they're first created. Client ids
1317 are handy when the model has not yet been saved to the server, and does not
1318 yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
1319 </p>
1320
1321 <p id="Model-attributes">
1322 <b class="header">attributes</b><code>model.attributes</code>
1323 <br />
1324 The <b>attributes</b> property is the internal hash containing the model's
1325 state &mdash; usually (but not necessarily) a form of the JSON object
1326 representing the model data on the server. It's often a straightforward
1327 serialization of a row from the database, but it could also be client-side
1328 computed state.
1329 </p>
1330
1331 <p>
1332 Please use <a href="#Model-set">set</a> to update the <b>attributes</b>
1333 instead of modifying them directly. If you'd like to retrieve and munge a
1334 copy of the model's attributes, use <tt>_.clone(model.attributes)</tt>
1335 instead.
1336 </p>
1337
1338 <p class="warning">
1339 Due to the fact that <a href="#Events">Events</a> accepts space separated
1340 lists of events, attribute names should not include spaces.
1341 </p>
1342
1343 <p id="Model-changed">
1344 <b class="header">changed</b><code>model.changed</code>
1345 <br />
1346 The <b>changed</b> property is the internal hash containing all the attributes
1347 that have changed since its last <a href="#Model-set">set</a>.
1348 Please do not update <b>changed</b> directly since its state is internally maintained
1349 by <a href="#Model-set">set</a>. A copy of <b>changed</b> can be acquired from
1350 <a href="#Model-changedAttributes">changedAttributes</a>.
1351 </p>
1352
1353 <p id="Model-defaults">
1354 <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
1355 <br />
1356 The <b>defaults</b> hash (or function) can be used to specify the default
1357 attributes for your model. When creating an instance of the model,
1358 any unspecified attributes will be set to their default value.
1359 </p>
1360
1361 <pre class="runnable">
1362 var Meal = Backbone.Model.extend({
1363 defaults: {
1364 "appetizer": "caesar salad",
1365 "entree": "ravioli",
1366 "dessert": "cheesecake"
1367 }
1368 });
1369
1370 alert("Dessert will be " + (new Meal).get('dessert'));
1371 </pre>
1372
1373 <p class="warning">
1374 Remember that in JavaScript, objects are passed by reference, so if you
1375 include an object as a default value, it will be shared among all instances.
1376 Instead, define <b>defaults</b> as a function.
1377 </p>
1378
1379 <p id="Model-toJSON">
1380 <b class="header">toJSON</b><code>model.toJSON([options])</code>
1381 <br />
1382 Return a shallow copy of the model's <a href="#Model-attributes">attributes</a>
1383 for JSON stringification. This can be used for persistence,
1384 serialization, or for augmentation before being sent to the server. The
1385 name of this method is a bit confusing, as it doesn't actually return a
1386 JSON string &mdash; but I'm afraid that it's the way that the
1387 <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior">JavaScript API for <b>JSON.stringify</b></a>
1388 works.
1389 </p>
1390
1391 <pre class="runnable">
1392 var artist = new Backbone.Model({
1393 firstName: "Wassily",
1394 lastName: "Kandinsky"
1395 });
1396
1397 artist.set({birthday: "December 16, 1866"});
1398
1399 alert(JSON.stringify(artist));
1400 </pre>
1401
1402 <p id="Model-sync">
1403 <b class="header">sync</b><code>model.sync(method, model, [options])</code>
1404 <br />
1405 Uses <a href="#Sync">Backbone.sync</a> to persist the state of a model to
1406 the server. Can be overridden for custom behavior.
1407 </p>
1408
1409 <p id="Model-fetch">
1410 <b class="header">fetch</b><code>model.fetch([options])</code>
1411 <br />
1412 Merges the model's state with attributes fetched from the server by
1413 delegating to <a href="#Sync">Backbone.sync</a>. Returns a
1414 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>.
1415 Useful if the model has never
1416 been populated with data, or if you'd like to ensure that you have the
1417 latest server state. Triggers a <tt>"change"</tt> event if the
1418 server's state differs from the current attributes. <tt>fetch</tt> accepts
1419 <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
1420 are both passed <tt>(model, response, options)</tt> as arguments.
1421 </p>
1422
1423 <pre>
1424 // Poll every 10 seconds to keep the channel model up-to-date.
1425 setInterval(function() {
1426 channel.fetch();
1427 }, 10000);
1428 </pre>
1429
1430 <p id="Model-save">
1431 <b class="header">save</b><code>model.save([attributes], [options])</code>
1432 <br />
1433 Save a model to your database (or alternative persistence layer),
1434 by delegating to <a href="#Sync">Backbone.sync</a>. Returns a
1435 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> if
1436 validation is successful and <tt>false</tt> otherwise. The <b>attributes</b>
1437 hash (as in <a href="#Model-set">set</a>) should contain the attributes
1438 you'd like to change &mdash; keys that aren't mentioned won't be altered &mdash; but,
1439 a <i>complete representation</i> of the resource will be sent to the server.
1440 As with <tt>set</tt>, you may pass individual keys and values instead of a hash.
1441 If the model has a <a href="#Model-validate">validate</a>
1442 method, and validation fails, the model will not be saved. If the model
1443 <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
1444 (HTTP <tt>POST</tt>), if the model already
1445 exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
1446 </p>
1447
1448 <p>
1449 If instead, you'd only like the <i>changed</i> attributes to be sent to the
1450 server, call <tt>model.save(attrs, {patch: true})</tt>. You'll get an HTTP
1451 <tt>PATCH</tt> request to the server with just the passed-in attributes.
1452 </p>
1453
1454 <p>
1455 Calling <tt>save</tt> with new attributes will cause a <tt>"change"</tt>
1456 event immediately, a <tt>"request"</tt> event as the Ajax request begins to
1457 go to the server, and a <tt>"sync"</tt> event after the server has acknowledged
1458 the successful change. Pass <tt>{wait: true}</tt> if you'd like to wait
1459 for the server before setting the new attributes on the model.
1460 </p>
1461
1462 <p>
1463 In the following example, notice how our overridden version
1464 of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
1465 the first time the model is saved and an <tt>"update"</tt>
1466 request the second time.
1467 </p>
1468
1469 <pre class="runnable">
1470 Backbone.sync = function(method, model) {
1471 alert(method + ": " + JSON.stringify(model));
1472 model.set('id', 1);
1473 };
1474
1475 var book = new Backbone.Model({
1476 title: "The Rough Riders",
1477 author: "Theodore Roosevelt"
1478 });
1479
1480 book.save();
1481
1482 book.save({author: "Teddy"});
1483 </pre>
1484
1485 <p>
1486 <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
1487 options hash, which will be passed the arguments <tt>(model, response, options)</tt>.
1488 If a server-side validation fails, return a non-<tt>200</tt>
1489 HTTP response code, along with an error response in text or JSON.
1490 </p>
1491
1492 <pre>
1493 book.save("author", "F.D.R.", {error: function(){ ... }});
1494 </pre>
1495
1496 <p id="Model-destroy">
1497 <b class="header">destroy</b><code>model.destroy([options])</code>
1498 <br />
1499 Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
1500 request to <a href="#Sync">Backbone.sync</a>. Returns a
1501 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> object, or
1502 <tt>false</tt> if the model <a href="#Model-isNew">isNew</a>. Accepts
1503 <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
1504 will be passed <tt>(model, response, options)</tt>.
1505 Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
1506 through any collections that contain it, a <tt>"request"</tt> event as it
1507 begins the Ajax request to the server, and a <tt>"sync"</tt> event, after
1508 the server has successfully acknowledged the model's deletion. Pass
1509 <tt>{wait: true}</tt> if you'd like to wait for the server to respond
1510 before removing the model from the collection.
1511 </p>
1512
1513 <pre>
1514 book.destroy({success: function(model, response) {
1515 ...
1516 }});
1517 </pre>
1518
1519 <p id="Model-Underscore-Methods">
1520 <b class="header">Underscore Methods (9)</b>
1521 <br />
1522 Backbone proxies to <b>Underscore.js</b> to provide 9 object functions
1523 on <b>Backbone.Model</b>. They aren't all documented here, but
1524 you can take a look at the Underscore documentation for the full details&hellip;
1525 </p>
1526
1527 <ul class="small">
1528 <li><a href="http://underscorejs.org/#keys">keys</a></li>
1529 <li><a href="http://underscorejs.org/#values">values</a></li>
1530 <li><a href="http://underscorejs.org/#pairs">pairs</a></li>
1531 <li><a href="http://underscorejs.org/#invert">invert</a></li>
1532 <li><a href="http://underscorejs.org/#pick">pick</a></li>
1533 <li><a href="http://underscorejs.org/#omit">omit</a></li>
1534 <li><a href="http://underscorejs.org/#chain">chain</a></li>
1535 <li><a href="http://underscorejs.org/#isEmpty">isEmpty</a></li>
1536 </ul>
1537
1538 <pre>
1539 user.pick('first_name', 'last_name', 'email');
1540
1541 chapters.keys().join(', ');
1542 </pre>
1543
1544 <p id="Model-validate">
1545 <b class="header">validate</b><code>model.validate(attributes, options)</code>
1546 <br />
1547 This method is left undefined and you're encouraged to override it with
1548 any custom validation logic you have that can be performed in JavaScript.
1549 If the attributes are valid, don't return anything from <b>validate</b>;
1550 if they are invalid return an error of your choosing. It can be as
1551 simple as a string error message to be displayed, or a complete error
1552 object that describes the error programmatically.
1553 </p>
1554
1555 <p>
1556 By default <tt>save</tt> checks <b>validate</b> before
1557 setting any attributes but you may also tell <tt>set</tt> to validate
1558 the new attributes by passing <tt>{validate: true}</tt> as an option.
1559 The <b>validate</b> method receives the model attributes as well as any
1560 options passed to <tt>set</tt> or <tt>save</tt>, if <b>validate</b>
1561 returns an error, <tt>save</tt> does not continue, the model attributes
1562 are not modified on the server, an <tt>"invalid"</tt> event is triggered,
1563 and the <tt>validationError</tt> property is set on the model with the
1564 value returned by this method.
1565 </p>
1566
1567 <pre class="runnable">
1568 var Chapter = Backbone.Model.extend({
1569 validate: function(attrs, options) {
1570 if (attrs.end &lt; attrs.start) {
1571 return "can't end before it starts";
1572 }
1573 }
1574 });
1575
1576 var one = new Chapter({
1577 title : "Chapter One: The Beginning"
1578 });
1579
1580 one.on("invalid", function(model, error) {
1581 alert(model.get("title") + " " + error);
1582 });
1583
1584 one.save({
1585 start: 15,
1586 end: 10
1587 });
1588 </pre>
1589
1590 <p>
1591 <tt>"invalid"</tt> events are useful for providing coarse-grained error
1592 messages at the model or collection level.
1593 </p>
1594
1595 <p id="Model-validationError">
1596 <b class="header">validationError</b><code>model.validationError</code>
1597 <br />
1598 The value returned by <a href="#Model-validate">validate</a> during the last failed validation.
1599 </p>
1600
1601 <p id="Model-isValid">
1602 <b class="header">isValid</b><code>model.isValid(options)</code>
1603 <br />
1604 Run <a href="#Model-validate">validate</a> to check the model state.
1605 </p>
1606
1607 <p>
1608 The <tt>validate</tt> method receives the model attributes as well as any
1609 options passed to <b>isValid</b>, if <tt>validate</tt> returns an error
1610 an <tt>"invalid"</tt> event is triggered, and the error is set on the
1611 model in the <tt>validationError</tt> property.
1612 </p>
1613
1614 <pre class="runnable">
1615 var Chapter = Backbone.Model.extend({
1616 validate: function(attrs, options) {
1617 if (attrs.end &lt; attrs.start) {
1618 return "can't end before it starts";
1619 }
1620 }
1621 });
1622
1623 var one = new Chapter({
1624 title : "Chapter One: The Beginning"
1625 });
1626
1627 one.set({
1628 start: 15,
1629 end: 10
1630 });
1631
1632 if (!one.isValid()) {
1633 alert(one.get("title") + " " + one.validationError);
1634 }
1635 </pre>
1636
1637 <p id="Model-url">
1638 <b class="header">url</b><code>model.url()</code>
1639 <br />
1640 Returns the relative URL where the model's resource would be located on
1641 the server. If your models are located somewhere else, override this method
1642 with the correct logic. Generates URLs of the form: <tt>"[collection.url]/[id]"</tt>
1643 by default, but you may override by specifying an explicit <tt>urlRoot</tt>
1644 if the model's collection shouldn't be taken into account.
1645 </p>
1646
1647 <p>
1648 Delegates to <a href="#Collection-url">Collection#url</a> to generate the
1649 URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
1650 property, if all models of this class share a common root URL.
1651 A model with an id of <tt>101</tt>, stored in a
1652 <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
1653 would have this URL: <tt>"/documents/7/notes/101"</tt>
1654 </p>
1655
1656 <p id="Model-urlRoot">
1657 <b class="header">urlRoot</b><code>model.urlRoot or model.urlRoot()</code>
1658 <br />
1659 Specify a <tt>urlRoot</tt> if you're using a model <i>outside</i> of a collection,
1660 to enable the default <a href="#Model-url">url</a> function to generate
1661 URLs based on the model id. <tt>"[urlRoot]/id"</tt><br />
1662 Normally, you won't need to define this.
1663 Note that <tt>urlRoot</tt> may also be a function.
1664 </p>
1665
1666 <pre class="runnable">
1667 var Book = Backbone.Model.extend({urlRoot : '/books'});
1668
1669 var solaris = new Book({id: "1083-lem-solaris"});
1670
1671 alert(solaris.url());
1672 </pre>
1673
1674 <p id="Model-parse">
1675 <b class="header">parse</b><code>model.parse(response, options)</code>
1676 <br />
1677 <b>parse</b> is called whenever a model's data is returned by the
1678 server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
1679 The function is passed the raw <tt>response</tt> object, and should return
1680 the attributes hash to be <a href="#Model-set">set</a> on the model. The
1681 default implementation is a no-op, simply passing through the JSON response.
1682 Override this if you need to work with a preexisting API, or better namespace
1683 your responses.
1684 </p>
1685
1686 <p>
1687 If you're working with a Rails backend that has a version prior to 3.1,
1688 you'll notice that its default <tt>to_json</tt> implementation includes
1689 a model's attributes under a namespace. To disable this behavior for
1690 seamless Backbone integration, set:
1691 </p>
1692
1693 <pre>
1694 ActiveRecord::Base.include_root_in_json = false
1695 </pre>
1696
1697 <p id="Model-clone">
1698 <b class="header">clone</b><code>model.clone()</code>
1699 <br />
1700 Returns a new instance of the model with identical attributes.
1701 </p>
1702
1703 <p id="Model-isNew">
1704 <b class="header">isNew</b><code>model.isNew()</code>
1705 <br />
1706 Has this model been saved to the server yet? If the model does not yet have
1707 an <tt>id</tt>, it is considered to be new.
1708 </p>
1709
1710 <p id="Model-hasChanged">
1711 <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
1712 <br />
1713 Has the model changed since its last <a href="#Model-set">set</a>? If an <b>attribute</b>
1714 is passed, returns <tt>true</tt> if that specific attribute has changed.
1715 </p>
1716
1717 <p class="warning">
1718 Note that this method, and the following change-related ones,
1719 are only useful during the course of a <tt>"change"</tt> event.
1720 </p>
1721
1722 <pre>
1723 book.on("change", function() {
1724 if (book.hasChanged("title")) {
1725 ...
1726 }
1727 });
1728 </pre>
1729
1730 <p id="Model-changedAttributes">
1731 <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
1732 <br />
1733 Retrieve a hash of only the model's attributes that have changed since the last
1734 <a href="#Model-set">set</a>, or <tt>false</tt> if there are none. Optionally, an external
1735 <b>attributes</b> hash can be passed in, returning the attributes in that
1736 hash which differ from the model. This can be used to figure out which
1737 portions of a view should be updated, or what calls
1738 need to be made to sync the changes to the server.
1739 </p>
1740
1741 <p id="Model-previous">
1742 <b class="header">previous</b><code>model.previous(attribute)</code>
1743 <br />
1744 During a <tt>"change"</tt> event, this method can be used to get the
1745 previous value of a changed attribute.
1746 </p>
1747
1748 <pre class="runnable">
1749 var bill = new Backbone.Model({
1750 name: "Bill Smith"
1751 });
1752
1753 bill.on("change:name", function(model, name) {
1754 alert("Changed name from " + bill.previous("name") + " to " + name);
1755 });
1756
1757 bill.set({name : "Bill Jones"});
1758 </pre>
1759
1760 <p id="Model-previousAttributes">
1761 <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
1762 <br />
1763 Return a copy of the model's previous attributes. Useful for getting a
1764 diff between versions of a model, or getting back to a valid state after
1765 an error occurs.
1766 </p>
1767
1768 <h2 id="Collection">Backbone.Collection</h2>
1769
1770 <p>
1771 Collections are ordered sets of models. You can bind <tt>"change"</tt> events
1772 to be notified when any model in the collection has been modified,
1773 listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
1774 the collection from the server, and use a full suite of
1775 <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
1776 </p>
1777
1778 <p>
1779 Any event that is triggered on a model in a collection will also be
1780 triggered on the collection directly, for convenience.
1781 This allows you to listen for changes to specific attributes in any
1782 model in a collection, for example:
1783 <tt>documents.on("change:selected", ...)</tt>
1784 </p>
1785
1786 <p id="Collection-extend">
1787 <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
1788 <br />
1789 To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
1790 providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
1791 directly to the collection's constructor function.
1792 </p>
1793
1794 <p id="Collection-model">
1795 <b class="header">model</b><code>collection.model([attrs], [options])</code>
1796 <br />
1797 Override this property to specify the model class that the collection contains.
1798 If defined, you can pass raw attributes objects (and arrays) and options to
1799 <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
1800 and <a href="#Collection-reset">reset</a>, and the attributes will be
1801 converted into a model of the proper type using the provided options, if any.
1802 </p>
1803
1804 <pre>
1805 var Library = Backbone.Collection.extend({
1806 model: Book
1807 });
1808 </pre>
1809
1810 <p>
1811 A collection can also contain polymorphic models by overriding this property
1812 with a constructor that returns a model.
1813 </p>
1814
1815 <pre>
1816 var Library = Backbone.Collection.extend({
1817
1818 model: function(attrs, options) {
1819 if (condition) {
1820 return new PublicDocument(attrs, options);
1821 } else {
1822 return new PrivateDocument(attrs, options);
1823 }
1824 }
1825
1826 });
1827 </pre>
1828
1829 <p id="Collection-modelId">
1830 <b class="header">modelId</b><code>collection.modelId(attrs, idAttribute)</code>
1831 <br />
1832 Override this method to return the value the collection will use to
1833 identify a model given its attributes. Useful for combining models from
1834 multiple tables with different <a href="#Model-idAttribute"><tt>idAttribute</tt></a>
1835 values into a single collection.
1836 </p>
1837
1838 <p>
1839 By default returns the value of the given
1840 <a href="#Model-idAttribute"><tt>idAttribute</tt></a>
1841 within the <tt>attrs</tt>, or failing that, <tt>id</tt>. If
1842 your collection uses a <a href="#Collection-model">model factory</a> and
1843 the id ranges of those models might collide, you must
1844 override this method.
1845 </p>
1846
1847 <pre class="runnable">
1848 var Library = Backbone.Collection.extend({
1849 modelId: function(attrs) {
1850 return attrs.type + attrs.id;
1851 }
1852 });
1853
1854 var library = new Library([
1855 {type: 'dvd', id: 1},
1856 {type: 'vhs', id: 1}
1857 ]);
1858
1859 var dvdId = library.get('dvd1').id;
1860 var vhsId = library.get('vhs1').id;
1861 alert('dvd: ' + dvdId + ', vhs: ' + vhsId);
1862 </pre>
1863
1864 <p id="Collection-preinitialize">
1865 <b class="header">preinitialize</b><code>new Backbone.Collection([models], [options])</code>
1866 <br />
1867 For use with collections as ES classes. If you define a <b>preinitialize</b>
1868 method, it will be invoked when the Collection is first created and before
1869 any instantiation logic is run for the Collection.
1870 </p>
1871
1872 <pre>
1873 class Library extends Backbone.Collection {
1874 preinitialize() {
1875 this.on("add", function() {
1876 console.log("Add model event got fired!");
1877 });
1878 }
1879 }
1880 </pre>
1881
1882 <p id="Collection-constructor">
1883 <b class="header">constructor / initialize</b><code>new Backbone.Collection([models], [options])</code>
1884 <br />
1885 When creating a Collection, you may choose to pass in the initial array
1886 of <b>models</b>. The collection's <a href="#Collection-comparator">comparator</a>
1887 may be included as an option. Passing <tt>false</tt> as the
1888 comparator option will prevent sorting. If you define an
1889 <b>initialize</b> function, it will be invoked when the collection is
1890 created. There are a couple of options that, if provided, are attached to
1891 the collection directly: <tt>model</tt> and <tt>comparator</tt>.<br />
1892 Pass <tt>null</tt> for <tt>models</tt> to create an empty Collection with <tt>options</tt>.
1893 </p>
1894
1895 <pre>
1896 var tabs = new TabSet([tab1, tab2, tab3]);
1897 var spaces = new Backbone.Collection(null, {
1898 model: Space
1899 });
1900 </pre>
1901
1902 <p id="Collection-models">
1903 <b class="header">models</b><code>collection.models</code>
1904 <br />
1905 Raw access to the JavaScript array of models inside of the collection. Usually you'll
1906 want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
1907 to access model objects, but occasionally a direct reference to the array
1908 is desired.
1909 </p>
1910
1911 <p id="Collection-toJSON">
1912 <b class="header">toJSON</b><code>collection.toJSON([options])</code>
1913 <br />
1914 Return an array containing the attributes hash of each model
1915 (via <a href="#Model-toJSON">toJSON</a>) in the
1916 collection. This can be used to serialize and persist the
1917 collection as a whole. The name of this method is a bit confusing, because
1918 it conforms to
1919 <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior">JavaScript's JSON API</a>.
1920 </p>
1921
1922 <pre class="runnable">
1923 var collection = new Backbone.Collection([
1924 {name: "Tim", age: 5},
1925 {name: "Ida", age: 26},
1926 {name: "Rob", age: 55}
1927 ]);
1928
1929 alert(JSON.stringify(collection));
1930 </pre>
1931
1932 <p id="Collection-sync">
1933 <b class="header">sync</b><code>collection.sync(method, collection, [options])</code>
1934 <br />
1935 Uses <a href="#Sync">Backbone.sync</a> to persist the state of a
1936 collection to the server. Can be overridden for custom behavior.
1937 </p>
1938
1939 <p id="Collection-Underscore-Methods">
1940 <b class="header">Underscore Methods (46)</b>
1941 <br />
1942 Backbone proxies to <b>Underscore.js</b> to provide 46 iteration functions
1943 on <b>Backbone.Collection</b>. They aren't all documented here, but
1944 you can take a look at the Underscore documentation for the full details&hellip;
1945 </p>
1946
1947 <p>
1948 Most methods can take an object or string to support model-attribute-style
1949 predicates or a function that receives the model instance as an argument.
1950 </p>
1951
1952 <ul class="small">
1953 <li><a href="http://underscorejs.org/#each">forEach (each)</a></li>
1954 <li><a href="http://underscorejs.org/#map">map (collect)</a></li>
1955 <li><a href="http://underscorejs.org/#reduce">reduce (foldl, inject)</a></li>
1956 <li><a href="http://underscorejs.org/#reduceRight">reduceRight (foldr)</a></li>
1957 <li><a href="http://underscorejs.org/#find">find (detect)</a></li>
1958 <li><a href="http://underscorejs.org/#findIndex">findIndex</a></li>
1959 <li><a href="http://underscorejs.org/#findLastIndex">findLastIndex</a></li>
1960 <li><a href="http://underscorejs.org/#filter">filter (select)</a></li>
1961 <li><a href="http://underscorejs.org/#reject">reject</a></li>
1962 <li><a href="http://underscorejs.org/#every">every (all)</a></li>
1963 <li><a href="http://underscorejs.org/#some">some (any)</a></li>
1964 <li><a href="http://underscorejs.org/#contains">contains (includes)</a></li>
1965 <li><a href="http://underscorejs.org/#invoke">invoke</a></li>
1966 <li><a href="http://underscorejs.org/#max">max</a></li>
1967 <li><a href="http://underscorejs.org/#min">min</a></li>
1968 <li><a href="http://underscorejs.org/#sortBy">sortBy</a></li>
1969 <li><a href="http://underscorejs.org/#groupBy">groupBy</a></li>
1970 <li><a href="http://underscorejs.org/#shuffle">shuffle</a></li>
1971 <li><a href="http://underscorejs.org/#toArray">toArray</a></li>
1972 <li><a href="http://underscorejs.org/#size">size</a></li>
1973 <li><a href="http://underscorejs.org/#first">first (head, take)</a></li>
1974 <li><a href="http://underscorejs.org/#initial">initial</a></li>
1975 <li><a href="http://underscorejs.org/#rest">rest (tail, drop)</a></li>
1976 <li><a href="http://underscorejs.org/#last">last</a></li>
1977 <li><a href="http://underscorejs.org/#without">without</a></li>
1978 <li><a href="http://underscorejs.org/#indexOf">indexOf</a></li>
1979 <li><a href="http://underscorejs.org/#lastIndexOf">lastIndexOf</a></li>
1980 <li><a href="http://underscorejs.org/#isEmpty">isEmpty</a></li>
1981 <li><a href="http://underscorejs.org/#chain">chain</a></li>
1982 <li><a href="http://underscorejs.org/#difference">difference</a></li>
1983 <li><a href="http://underscorejs.org/#sample">sample</a></li>
1984 <li><a href="http://underscorejs.org/#partition">partition</a></li>
1985 <li><a href="http://underscorejs.org/#countBy">countBy</a></li>
1986 <li><a href="http://underscorejs.org/#indexBy">indexBy</a></li>
1987 </ul>
1988
1989 <pre>
1990 books.each(function(book) {
1991 book.publish();
1992 });
1993
1994 var titles = books.map("title");
1995
1996 var publishedBooks = books.filter({published: true});
1997
1998 var alphabetical = books.sortBy(function(book) {
1999 return book.author.get("name").toLowerCase();
2000 });
2001
2002 var randomThree = books.sample(3);
2003 </pre>
2004
2005 <p id="Collection-add">
2006 <b class="header">add</b><code>collection.add(models, [options])</code>
2007 <br />
2008 Add a model (or an array of models) to the collection, firing an <tt>"add"</tt>
2009 event for each model, and an <tt>"update"</tt> event afterwards. If a <a href="#Collection-model">model</a> property is defined, you may also pass
2010 raw attributes objects and options, and have them be vivified as instances of the model using
2011 the provided options.
2012 Returns the added (or preexisting, if duplicate) models.
2013 Pass <tt>{at: index}</tt> to splice the model into the collection at the
2014 specified <tt>index</tt>. If you're adding models to the collection that are
2015 <i>already</i> in the collection, they'll be ignored, unless you pass
2016 <tt>{merge: true}</tt>, in which case their attributes will be merged
2017 into the corresponding models, firing any appropriate <tt>"change"</tt> events.
2018 </p>
2019
2020 <pre class="runnable">
2021 var ships = new Backbone.Collection;
2022
2023 ships.on("add", function(ship) {
2024 alert("Ahoy " + ship.get("name") + "!");
2025 });
2026
2027 ships.add([
2028 {name: "Flying Dutchman"},
2029 {name: "Black Pearl"}
2030 ]);
2031 </pre>
2032
2033 <p class="warning">
2034 Note that adding the same model (a model with the same <tt>id</tt>) to
2035 a collection more than once <br /> is a no-op.
2036 </p>
2037
2038 <p id="Collection-remove">
2039 <b class="header">remove</b><code>collection.remove(models, [options])</code>
2040 <br />
2041 Remove a model (or an array of models) from the collection, and return
2042 them. Each model can be a Model instance, an <tt>id</tt> string or a JS
2043 object, any value acceptable as the <tt>id</tt> argument of
2044 <a href="#Collection-get"><tt>collection.get</tt></a>.
2045 Fires a <tt>"remove"</tt> event for each model, and a single
2046 <tt>"update"</tt> event afterwards, unless <tt>{silent: true}</tt> is passed.
2047 The model's index before removal is available to listeners as
2048 <tt>options.index</tt>.
2049 </p>
2050
2051 <p id="Collection-reset">
2052 <b class="header">reset</b><code>collection.reset([models], [options])</code>
2053 <br />
2054 Adding and removing models one at a time is all well and good, but sometimes
2055 you have so many models to change that you'd rather just update the collection
2056 in bulk. Use <b>reset</b> to replace a collection with a new list
2057 of models (or attribute hashes), triggering a single <tt>"reset"</tt> event
2058 on completion, and <i>without</i> triggering any add or remove events on any models.
2059 Returns the newly-set models.
2060 For convenience, within a <tt>"reset"</tt> event, the list of any
2061 previous models is available as <tt>options.previousModels</tt>.<br />
2062 Pass <tt>null</tt> for <tt>models</tt> to empty your Collection with <tt>options</tt>.
2063 </p>
2064
2065 <p>
2066 Here's an example using <b>reset</b> to bootstrap a collection during initial page load,
2067 in a Rails application:
2068 </p>
2069
2070 <pre>
2071 &lt;script&gt;
2072 var accounts = new Backbone.Collection;
2073 accounts.reset(&lt;%= @accounts.to_json %&gt;);
2074 &lt;/script&gt;
2075 </pre>
2076
2077 <p>
2078 Calling <tt>collection.reset()</tt> without passing any models as arguments
2079 will empty the entire collection.
2080 </p>
2081
2082 <p id="Collection-set">
2083 <b class="header">set</b><code>collection.set(models, [options])</code>
2084 <br />
2085 The <b>set</b> method performs a "smart" update of the collection
2086 with the passed list of models. If a model in the list isn't yet in the
2087 collection it will be added; if the model is already in the collection
2088 its attributes will be merged; and if the collection contains any models that
2089 <i>aren't</i> present in the list, they'll be removed. All of the appropriate
2090 <tt>"add"</tt>, <tt>"remove"</tt>, and <tt>"change"</tt> events are fired
2091 as this happens. Returns the touched models in the collection.
2092 If you'd like to customize the behavior, you can disable
2093 it with options: <tt>{add: false}</tt>, <tt>{remove: false}</tt>, or <tt>{merge: false}</tt>.
2094 </p>
2095
2096 <pre>
2097 var vanHalen = new Backbone.Collection([eddie, alex, stone, roth]);
2098
2099 vanHalen.set([eddie, alex, stone, hagar]);
2100
2101 // Fires a "remove" event for roth, and an "add" event for "hagar".
2102 // Updates any of stone, alex, and eddie's attributes that may have
2103 // changed over the years.
2104 </pre>
2105
2106 <p id="Collection-get">
2107 <b class="header">get</b><code>collection.get(id)</code>
2108 <br />
2109 Get a model from a collection, specified by an <a href="#Model-id">id</a>,
2110 a <a href="#Model-cid">cid</a>, or by passing in a <b>model</b>.
2111 </p>
2112
2113 <pre>
2114 var book = library.get(110);
2115 </pre>
2116
2117 <p id="Collection-at">
2118 <b class="header">at</b><code>collection.at(index)</code>
2119 <br />
2120 Get a model from a collection, specified by index. Useful if your collection
2121 is sorted, and if your collection isn't sorted, <b>at</b> will still
2122 retrieve models in insertion order. When passed a negative index, it
2123 will retrieve the model from the back of the collection.
2124 </p>
2125
2126 <p id="Collection-push">
2127 <b class="header">push</b><code>collection.push(model, [options])</code>
2128 <br />
2129 Add a model at the end of a collection. Takes the same options as
2130 <a href="#Collection-add">add</a>.
2131 </p>
2132
2133 <p id="Collection-pop">
2134 <b class="header">pop</b><code>collection.pop([options])</code>
2135 <br />
2136 Remove and return the last model from a collection. Takes the same options as
2137 <a href="#Collection-remove">remove</a>.
2138 </p>
2139
2140 <p id="Collection-unshift">
2141 <b class="header">unshift</b><code>collection.unshift(model, [options])</code>
2142 <br />
2143 Add a model at the beginning of a collection. Takes the same options as
2144 <a href="#Collection-add">add</a>.
2145 </p>
2146
2147 <p id="Collection-shift">
2148 <b class="header">shift</b><code>collection.shift([options])</code>
2149 <br />
2150 Remove and return the first model from a collection. Takes the same options as
2151 <a href="#Collection-remove">remove</a>.
2152 </p>
2153
2154 <p id="Collection-slice">
2155 <b class="header">slice</b><code>collection.slice(begin, end)</code>
2156 <br />
2157 Return a shallow copy of this collection's models, using the same options as
2158 native
2159 <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">Array#slice</a>.
2160 </p>
2161
2162 <p id="Collection-length">
2163 <b class="header">length</b><code>collection.length</code>
2164 <br />
2165 Like an array, a Collection maintains a <tt>length</tt> property, counting
2166 the number of models it contains.
2167 </p>
2168
2169 <p id="Collection-comparator">
2170 <b class="header">comparator</b><code>collection.comparator</code>
2171 <br />
2172 By default there is no <b>comparator</b> for a collection.
2173 If you define a comparator, it will be used to sort the collection any
2174 time a model is added.
2175 A comparator can be defined as a
2176 <a href="http://underscorejs.org/#sortBy">sortBy</a>
2177 (pass a function that takes a single argument),
2178 as a
2179 <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">sort</a>
2180 (pass a comparator function that expects two arguments),
2181 or as a string indicating the attribute to sort by.
2182 </p>
2183
2184 <p>
2185 "sortBy" comparator functions take a model and return a numeric or string
2186 value by which the model should be ordered relative to others.
2187 "sort" comparator functions take two models, and return <tt>-1</tt> if
2188 the first model should come before the second, <tt>0</tt> if they are of
2189 the same rank and <tt>1</tt> if the first model should come after.
2190 <i>Note that Backbone depends on the arity of your comparator function to
2191 determine between the two styles, so be careful if your comparator function
2192 is bound.</i>
2193 </p>
2194
2195 <p>
2196 Note how even though all of the chapters in this example are added backwards,
2197 they come out in the proper order:
2198 </p>
2199
2200 <pre class="runnable">
2201 var Chapter = Backbone.Model;
2202 var chapters = new Backbone.Collection;
2203
2204 chapters.comparator = 'page';
2205
2206 chapters.add(new Chapter({page: 9, title: "The End"}));
2207 chapters.add(new Chapter({page: 5, title: "The Middle"}));
2208 chapters.add(new Chapter({page: 1, title: "The Beginning"}));
2209
2210 alert(chapters.pluck('title'));
2211 </pre>
2212
2213 <p class="warning">
2214 Collections with a comparator will not automatically re-sort if you
2215 later change model attributes, so you may wish to call
2216 <tt>sort</tt> after changing model attributes that would affect the order.
2217 </p>
2218
2219 <p id="Collection-sort">
2220 <b class="header">sort</b><code>collection.sort([options])</code>
2221 <br />
2222 Force a collection to re-sort itself. Note that a collection with a
2223 <a href="#Collection-comparator">comparator</a> will sort itself
2224 automatically whenever a model is added. To disable sorting when adding
2225 a model, pass <tt>{sort: false}</tt> to <tt>add</tt>. Calling <b>sort</b>
2226 triggers a <tt>"sort"</tt> event on the collection.
2227 </p>
2228
2229 <p id="Collection-pluck">
2230 <b class="header">pluck</b><code>collection.pluck(attribute)</code>
2231 <br />
2232 Pluck an attribute from each model in the collection. Equivalent to calling
2233 <tt>map</tt> and returning a single attribute from the iterator.
2234 </p>
2235
2236 <pre class="runnable">
2237 var stooges = new Backbone.Collection([
2238 {name: "Curly"},
2239 {name: "Larry"},
2240 {name: "Moe"}
2241 ]);
2242
2243 var names = stooges.pluck("name");
2244
2245 alert(JSON.stringify(names));
2246 </pre>
2247
2248 <p id="Collection-where">
2249 <b class="header">where</b><code>collection.where(attributes)</code>
2250 <br />
2251 Return an array of all the models in a collection that match the
2252 passed <b>attributes</b>. Useful for simple cases of <tt>filter</tt>.
2253 </p>
2254
2255 <pre class="runnable">
2256 var friends = new Backbone.Collection([
2257 {name: "Athos", job: "Musketeer"},
2258 {name: "Porthos", job: "Musketeer"},
2259 {name: "Aramis", job: "Musketeer"},
2260 {name: "d'Artagnan", job: "Guard"},
2261 ]);
2262
2263 var musketeers = friends.where({job: "Musketeer"});
2264
2265 alert(musketeers.length);
2266 </pre>
2267
2268 <p id="Collection-findWhere">
2269 <b class="header">findWhere</b><code>collection.findWhere(attributes)</code>
2270 <br />
2271 Just like <a href="#Collection-where">where</a>, but directly returns only
2272 the first model in the collection that matches the passed <b>attributes</b>.
2273 If no model matches returns <tt>undefined</tt>.
2274 </p>
2275
2276 <p id="Collection-url">
2277 <b class="header">url</b><code>collection.url or collection.url()</code>
2278 <br />
2279 Set the <b>url</b> property (or function) on a collection to reference
2280 its location on the server. Models within the collection will use <b>url</b>
2281 to construct URLs of their own.
2282 </p>
2283
2284 <pre>
2285 var Notes = Backbone.Collection.extend({
2286 url: '/notes'
2287 });
2288
2289 // Or, something more sophisticated:
2290
2291 var Notes = Backbone.Collection.extend({
2292 url: function() {
2293 return this.document.url() + '/notes';
2294 }
2295 });
2296 </pre>
2297
2298 <p id="Collection-parse">
2299 <b class="header">parse</b><code>collection.parse(response, options)</code>
2300 <br />
2301 <b>parse</b> is called by Backbone whenever a collection's models are
2302 returned by the server, in <a href="#Collection-fetch">fetch</a>.
2303 The function is passed the raw <tt>response</tt> object, and should return
2304 the array of model attributes to be <a href="#Collection-add">added</a>
2305 to the collection. The default implementation is a no-op, simply passing
2306 through the JSON response. Override this if you need to work with a
2307 preexisting API, or better namespace your responses.
2308 </p>
2309
2310 <pre>
2311 var Tweets = Backbone.Collection.extend({
2312 // The Twitter Search API returns tweets under "results".
2313 parse: function(response) {
2314 return response.results;
2315 }
2316 });
2317 </pre>
2318
2319 <p id="Collection-clone">
2320 <b class="header">clone</b><code>collection.clone()</code>
2321 <br />
2322 Returns a new instance of the collection with an identical list of models.
2323 </p>
2324
2325 <p id="Collection-fetch">
2326 <b class="header">fetch</b><code>collection.fetch([options])</code>
2327 <br />
2328 Fetch the default set of models for this collection from the server,
2329 <a href="#Collection-set">setting</a> them on the collection when they arrive.
2330 The <b>options</b> hash takes <tt>success</tt> and <tt>error</tt> callbacks
2331 which will both be passed <tt>(collection, response, options)</tt> as arguments.
2332 When the model data returns from the server, it uses <a href="#Collection-set">set</a>
2333 to (intelligently) merge the fetched models, unless you pass <tt>{reset: true}</tt>,
2334 in which case the collection will be (efficiently) <a href="#Collection-reset">reset</a>.
2335 Delegates to <a href="#Sync">Backbone.sync</a>
2336 under the covers for custom persistence strategies and returns a
2337 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>.
2338 The server handler for <b>fetch</b> requests should return a JSON array of
2339 models.
2340 </p>
2341
2342 <pre class="runnable">
2343 Backbone.sync = function(method, model) {
2344 alert(method + ": " + model.url);
2345 };
2346
2347 var accounts = new Backbone.Collection;
2348 accounts.url = '/accounts';
2349
2350 accounts.fetch();
2351 </pre>
2352
2353 <p>
2354 The behavior of <b>fetch</b> can be customized by using the available
2355 <a href="#Collection-set">set</a> options. For example, to fetch a
2356 collection, getting an <tt>"add"</tt> event for every new model, and
2357 a <tt>"change"</tt> event for every changed existing model, without
2358 removing anything: <tt>collection.fetch({remove: false})</tt>
2359 </p>
2360
2361 <p>
2362 <b>jQuery.ajax</b> options can also be passed directly as <b>fetch</b> options,
2363 so to fetch a specific page of a paginated collection:
2364 <tt>Documents.fetch({data: {page: 3}})</tt>
2365 </p>
2366
2367 <p>
2368 Note that <b>fetch</b> should not be used to populate collections on
2369 page load &mdash; all models needed at load time should already be
2370 <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
2371 intended for lazily-loading models for interfaces that are not needed
2372 immediately: for example, documents with collections of notes that may be
2373 toggled open and closed.
2374 </p>
2375
2376 <p id="Collection-create">
2377 <b class="header">create</b><code>collection.create(attributes, [options])</code>
2378 <br />
2379 Convenience to create a new instance of a model within a collection.
2380 Equivalent to instantiating a model with a hash of attributes,
2381 saving the model to the server, and adding the model to the set after being
2382 successfully created. Returns the new model. If client-side validation
2383 failed, the model will be unsaved, with validation errors.
2384 In order for this to work, you should set the
2385 <a href="#Collection-model">model</a> property of the collection.
2386 The <b>create</b> method can accept either an attributes hash and options to be
2387 passed down during model instantiation or an existing, unsaved model object.
2388 </p>
2389
2390 <p>
2391 Creating a model will cause an immediate <tt>"add"</tt> event to be
2392 triggered on the collection, a <tt>"request"</tt> event as the new model is
2393 sent to the server, as well as a <tt>"sync"</tt> event, once the
2394 server has responded with the successful creation of the model. Pass <tt>{wait: true}</tt>
2395 if you'd like to wait for the server before adding the new model to the collection.
2396 </p>
2397
2398 <pre>
2399 var Library = Backbone.Collection.extend({
2400 model: Book
2401 });
2402
2403 var nypl = new Library;
2404
2405 var othello = nypl.create({
2406 title: "Othello",
2407 author: "William Shakespeare"
2408 });
2409 </pre>
2410
2411 <p id="Collection-mixin">
2412 <b class="header">mixin</b><code>Backbone.Collection.mixin(properties)</code>
2413 <br />
2414 <code>mixin</code> provides a way to enhance the base <b>Backbone.Collection</b>
2415 and any collections which extend it. This can be used to add generic methods
2416 (e.g. additional <a href="#Collection-Underscore-Methods"><b>Underscore Methods</b></a>).
2417 </p>
2418
2419 <pre>
2420 Backbone.Collection.mixin({
2421 sum: function(models, iteratee) {
2422 return _.reduce(models, function(s, m) {
2423 return s + iteratee(m);
2424 }, 0);
2425 }
2426 });
2427
2428 var cart = new Backbone.Collection([
2429 {price: 16, name: 'monopoly'},
2430 {price: 5, name: 'deck of cards'},
2431 {price: 20, name: 'chess'}
2432 ]);
2433
2434 var cost = cart.sum('price');
2435 </pre>
2436
2437 <h2 id="Router">Backbone.Router</h2>
2438
2439 <p>
2440 Web applications often provide linkable, bookmarkable, shareable URLs for
2441 important locations in the app. Until recently, hash fragments
2442 (<tt>#page</tt>) were used to provide these permalinks, but with the
2443 arrival of the History API, it's now possible to use standard URLs (<tt>/page</tt>).
2444 <b>Backbone.Router</b> provides methods for routing client-side pages, and
2445 connecting them to actions and events. For browsers which don't yet support
2446 the History API, the Router handles graceful fallback and transparent
2447 translation to the fragment version of the URL.
2448 </p>
2449
2450 <p>
2451 During page load, after your application has finished creating all of its routers,
2452 be sure to call <tt>Backbone.history.start()</tt> or
2453 <tt>Backbone.history.start({pushState: true})</tt> to route the initial URL.
2454 </p>
2455
2456 <p id="Router-extend">
2457 <b class="header">extend</b><code>Backbone.Router.extend(properties, [classProperties])</code>
2458 <br />
2459 Get started by creating a custom router class. Define action functions that are
2460 triggered when certain URL fragments are
2461 matched, and provide a <a href="#Router-routes">routes</a> hash
2462 that pairs routes to actions. Note that you'll want to avoid using a
2463 leading slash in your route definitions:
2464 </p>
2465
2466 <pre>
2467 var Workspace = Backbone.Router.extend({
2468
2469 routes: {
2470 "help": "help", // #help
2471 "search/:query": "search", // #search/kiwis
2472 "search/:query/p:page": "search" // #search/kiwis/p7
2473 },
2474
2475 help: function() {
2476 ...
2477 },
2478
2479 search: function(query, page) {
2480 ...
2481 }
2482
2483 });
2484 </pre>
2485
2486 <p id="Router-routes">
2487 <b class="header">routes</b><code>router.routes</code>
2488 <br />
2489 The routes hash maps URLs with parameters to functions on your router
2490 (or just direct function definitions, if you prefer),
2491 similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
2492 Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
2493 component between slashes; and splat parts <tt>*splat</tt>, which can match
2494 any number of URL components. Part of a route can be made optional by
2495 surrounding it in parentheses <tt>(/:optional)</tt>.
2496 </p>
2497
2498 <p>
2499 For example, a route of <tt>"search/:query/p:page"</tt> will match
2500 a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
2501 and <tt>"2"</tt> to the action as positional arguments.
2502 </p>
2503
2504 <p>
2505 A route of <tt>"file/*path"</tt> will match
2506 <tt>#file/folder/file.txt</tt>, passing
2507 <tt>"folder/file.txt"</tt> to the action.
2508 </p>
2509
2510 <p>
2511 A route of <tt>"docs/:section(/:subsection)"</tt> will match
2512 <tt>#docs/faq</tt> and <tt>#docs/faq/installing</tt>, passing
2513 <tt>"faq"</tt> to the action in the first case, and passing <tt>"faq"</tt>
2514 and <tt>"installing"</tt> to the action in the second.
2515 </p>
2516
2517 <p>
2518 A nested optional route of <tt>"docs(/:section)(/:subsection)"</tt> will match
2519 <tt>#docs</tt>, <tt>#docs/faq</tt>, and <tt>#docs/faq/installing</tt>,
2520 passing <tt>"faq"</tt> to the action in the second case, and passing <tt>"faq"</tt>
2521 and <tt>"installing"</tt> to the action in the third.
2522 </p>
2523
2524 <p>
2525 Trailing slashes are treated as part of the URL, and (correctly) treated
2526 as a unique route when accessed. <tt>docs</tt> and <tt>docs/</tt> will fire
2527 different callbacks. If you can't avoid generating both types of URLs, you
2528 can define a <tt>"docs(/)"</tt> matcher to capture both cases.
2529 </p>
2530
2531 <p>
2532 When the visitor presses the back button, or enters a URL, and a particular
2533 route is matched, the name of the action will be fired as an
2534 <a href="#Events">event</a>, so that other objects can listen to the router,
2535 and be notified. In the following example, visiting <tt>#help/uploading</tt>
2536 will fire a <tt>route:help</tt> event from the router.
2537 </p>
2538
2539 <pre>
2540 routes: {
2541 "help/:page": "help",
2542 "download/*path": "download",
2543 "folder/:name": "openFolder",
2544 "folder/:name-:mode": "openFolder"
2545 }
2546 </pre>
2547
2548 <pre>
2549 router.on("route:help", function(page) {
2550 ...
2551 });
2552 </pre>
2553
2554 <p id="Router-preinitialize">
2555 <b class="header">preinitialize</b><code>new Backbone.Router([options])</code>
2556 <br />
2557 For use with routers as ES classes. If you define a <b>preinitialize</b>
2558 method, it will be invoked when the Router is first created and before
2559 any instantiation logic is run for the Router.
2560 </p>
2561
2562 <pre>
2563 class Router extends Backbone.Router {
2564 preinitialize() {
2565 // Override execute method
2566 this.execute = function(callback, args, name) {
2567 if (!loggedIn) {
2568 goToLogin();
2569 return false;
2570 }
2571 args.push(parseQueryString(args.pop()));
2572 if (callback) callback.apply(this, args);
2573 }
2574 }
2575 }
2576 </pre>
2577
2578 <p id="Router-constructor">
2579 <b class="header">constructor / initialize</b><code>new Router([options])</code>
2580 <br />
2581 When creating a new router, you may pass its
2582 <a href="#Router-routes">routes</a> hash directly as an option, if you
2583 choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
2584 function, if defined.
2585 </p>
2586
2587 <p id="Router-route">
2588 <b class="header">route</b><code>router.route(route, name, [callback])</code>
2589 <br />
2590 Manually create a route for the router, The <tt>route</tt> argument may
2591 be a <a href="#Router-routes">routing string</a> or regular expression.
2592 Each matching capture from the route or regular expression will be passed as
2593 an argument to the callback. The <tt>name</tt> argument will be triggered as
2594 a <tt>"route:name"</tt> event whenever the route is matched. If the
2595 <tt>callback</tt> argument is omitted <tt>router[name]</tt> will be used
2596 instead. Routes added later may override previously declared routes.
2597 </p>
2598
2599 <pre>
2600 initialize: function(options) {
2601
2602 // Matches #page/10, passing "10"
2603 this.route("page/:number", "page", function(number){ ... });
2604
2605 // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open
2606 this.route(/^(.*?)\/open$/, "open");
2607
2608 },
2609
2610 open: function(id) { ... }
2611 </pre>
2612
2613 <p id="Router-navigate">
2614 <b class="header">navigate</b><code>router.navigate(fragment, [options])</code>
2615 <br />
2616 Whenever you reach a point in your application that you'd like to save
2617 as a URL, call <b>navigate</b> in order to update the URL.
2618 If you also wish to call the route function, set the <b>trigger</b>
2619 option to <tt>true</tt>.
2620 To update the URL without creating an entry in the browser's history,
2621 set the <b>replace</b> option to <tt>true</tt>.
2622 </p>
2623
2624 <pre>
2625 openPage: function(pageNumber) {
2626 this.document.pages.at(pageNumber).open();
2627 this.navigate("page/" + pageNumber);
2628 }
2629
2630 # Or ...
2631
2632 app.navigate("help/troubleshooting", {trigger: true});
2633
2634 # Or ...
2635
2636 app.navigate("help/troubleshooting", {trigger: true, replace: true});
2637 </pre>
2638
2639 <p id="Router-execute">
2640 <b class="header">execute</b><code>router.execute(callback, args, name)</code>
2641 <br />
2642 This method is called internally within the router, whenever a route
2643 matches and its corresponding <b>callback</b> is about to be executed.
2644 Return <b>false</b> from execute to cancel the current transition.
2645 Override it to perform custom parsing or wrapping of your routes, for
2646 example, to parse query strings before handing them to your route
2647 callback, like so:
2648 </p>
2649
2650 <pre>
2651 var Router = Backbone.Router.extend({
2652 execute: function(callback, args, name) {
2653 if (!loggedIn) {
2654 goToLogin();
2655 return false;
2656 }
2657 args.push(parseQueryString(args.pop()));
2658 if (callback) callback.apply(this, args);
2659 }
2660 });
2661 </pre>
2662
2663 <h2 id="History">Backbone.history</h2>
2664
2665 <p>
2666 <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
2667 events or <tt>pushState</tt>, match the appropriate route, and trigger callbacks.
2668 You shouldn't ever have to create one of these yourself since <tt>Backbone.history</tt>
2669 already contains one.
2670 </p>
2671
2672 <p>
2673 <b>pushState</b> support exists on a purely opt-in basis in Backbone.
2674 Older browsers that don't support <tt>pushState</tt> will continue to use
2675 hash-based URL fragments, and if a hash URL is visited by a
2676 <tt>pushState</tt>-capable browser, it will be transparently upgraded to
2677 the true URL. Note that using real URLs requires your web server to be
2678 able to correctly render those pages, so back-end changes are required
2679 as well. For example, if you have a route of <tt>/documents/100</tt>,
2680 your web server must be able to serve that page, if the browser
2681 visits that URL directly. For full search-engine crawlability, it's best to
2682 have the server generate the complete HTML for the page ... but if it's a web
2683 application, just rendering the same content you would have for the root URL,
2684 and filling in the rest with Backbone Views and JavaScript works fine.
2685 </p>
2686
2687 <p id="History-start">
2688 <b class="header">start</b><code>Backbone.history.start([options])</code>
2689 <br />
2690 When all of your <a href="#Router">Routers</a> have been created,
2691 and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
2692 to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
2693 Subsequent calls to <tt>Backbone.history.start()</tt> will throw an error,
2694 and <tt>Backbone.History.started</tt> is a boolean value indicating whether
2695 it has already been called.
2696 </p>
2697
2698 <p>
2699 To indicate that you'd like to use HTML5 <tt>pushState</tt> support in
2700 your application, use <tt>Backbone.history.start({pushState: true})</tt>.
2701 If you'd like to use <tt>pushState</tt>, but have browsers that don't support
2702 it natively use full page refreshes instead, you can add
2703 <tt>{hashChange: false}</tt> to the options.
2704 </p>
2705
2706 <p>
2707 If your application is not being served from the root url <tt>/</tt> of your
2708 domain, be sure to tell History where the root really is, as an option:
2709 <tt>Backbone.history.start({pushState: true, root: "/public/search/"})</tt>
2710 </p>
2711
2712 <p>
2713 When called, if a route succeeds with a match for the current URL,
2714 <tt>Backbone.history.start()</tt> returns <tt>true</tt>. If no defined
2715 route matches the current URL, it returns <tt>false</tt>.
2716 </p>
2717
2718 <p>
2719 If the server has already rendered the entire page, and you don't want the
2720 initial route to trigger when starting History, pass <tt>silent: true</tt>.
2721 </p>
2722
2723 <p>
2724 Because hash-based history in Internet Explorer relies on an
2725 <tt>&lt;iframe&gt;</tt>, be sure to call <tt>start()</tt> only after the DOM
2726 is ready.
2727 </p>
2728
2729 <pre>
2730 $(function(){
2731 new WorkspaceRouter();
2732 new HelpPaneRouter();
2733 Backbone.history.start({pushState: true});
2734 });
2735 </pre>
2736
2737 <h2 id="Sync">Backbone.sync</h2>
2738
2739 <p>
2740 <b>Backbone.sync</b> is the function that Backbone calls every time it
2741 attempts to read or save a model to the server. By default, it uses
2742 <tt>jQuery.ajax</tt> to make a RESTful JSON request and returns a
2743 <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>. You can override
2744 it in order to use a different persistence strategy, such as WebSockets,
2745 XML transport, or Local Storage.
2746 </p>
2747
2748 <p>
2749 The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, [options])</tt>
2750 </p>
2751
2752 <ul>
2753 <li><b>method</b> – the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
2754 <li><b>model</b> – the model to be saved (or collection to be read)</li>
2755 <li><b>options</b> – success and error callbacks, and all other jQuery request options</li>
2756 </ul>
2757
2758 <p>
2759 With the default implementation, when <b>Backbone.sync</b> sends up a request to save
2760 a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
2761 with content-type <tt>application/json</tt>. When returning a JSON response,
2762 send down the attributes of the model that have been changed by the server, and need
2763 to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
2764 (<a href="#Collection-fetch">Collection#fetch</a>), send down an array
2765 of model attribute objects.
2766 </p>
2767
2768 <p>
2769 Whenever a model or collection begins a <b>sync</b> with the server, a
2770 <tt>"request"</tt> event is emitted. If the request completes successfully
2771 you'll get a <tt>"sync"</tt> event, and an <tt>"error"</tt> event if not.
2772 </p>
2773
2774 <p>
2775 The <b>sync</b> function may be overridden globally as <tt>Backbone.sync</tt>,
2776 or at a finer-grained level, by adding a <tt>sync</tt> function to a Backbone
2777 collection or to an individual model.
2778 </p>
2779
2780 <p>
2781 The default <b>sync</b> handler maps CRUD to REST like so:
2782 </p>
2783
2784 <ul>
2785 <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
2786 <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
2787 <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
2788 <li><b>patch &rarr; PATCH &nbsp; </b><tt>/collection/id</tt></li>
2789 <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
2790 </ul>
2791
2792 <p>
2793 As an example, a Rails 4 handler responding to an <tt>"update"</tt> call from
2794 <tt>Backbone</tt> might look like this:
2795 </p>
2796
2797 <pre>
2798 def update
2799 account = Account.find params[:id]
2800 permitted = params.require(:account).permit(:name, :otherparam)
2801 account.update_attributes permitted
2802 render :json => account
2803 end
2804 </pre>
2805
2806 <p>
2807 One more tip for integrating Rails versions prior to 3.1 is to disable
2808 the default namespacing for <tt>to_json</tt> calls on models by setting
2809 <tt>ActiveRecord::Base.include_root_in_json = false</tt>
2810 </p>
2811
2812 <p id="Sync-ajax">
2813 <b class="header">ajax</b><code>Backbone.ajax = function(request) { ... };</code>
2814 <br />
2815 If you want to use a custom AJAX function, or your endpoint doesn't support
2816 the <a href="http://api.jquery.com/jQuery.ajax/">jQuery.ajax</a> API
2817 and you need to tweak things, you can do so by setting <tt>Backbone.ajax</tt>.
2818 </p>
2819
2820 <p id="Sync-emulateHTTP">
2821 <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
2822 <br />
2823 If you want to work with a legacy web server that doesn't support Backbone's
2824 default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
2825 Setting this option will fake <tt>PUT</tt>, <tt>PATCH</tt> and <tt>DELETE</tt> requests with
2826 a HTTP <tt>POST</tt>, setting the <tt>X-HTTP-Method-Override</tt> header
2827 with the true method. If <tt>emulateJSON</tt> is also on, the true method
2828 will be passed as an additional <tt>_method</tt> parameter.
2829 </p>
2830
2831 <pre>
2832 Backbone.emulateHTTP = true;
2833
2834 model.save(); // POST to "/collection/id", with "_method=PUT" + header.
2835 </pre>
2836
2837 <p id="Sync-emulateJSON">
2838 <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
2839 <br />
2840 If you're working with a legacy web server that can't handle requests
2841 encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
2842 will cause the JSON to be serialized under a <tt>model</tt> parameter, and
2843 the request to be made with a <tt>application/x-www-form-urlencoded</tt>
2844 MIME type, as if from an HTML form.
2845 </p>
2846
2847 <h2 id="View">Backbone.View</h2>
2848
2849 <p>
2850 Backbone views are almost more convention than they are code &mdash; they
2851 don't determine anything about your HTML or CSS for you, and can be used
2852 with any JavaScript templating library.
2853 The general idea is to organize your interface into logical views,
2854 backed by models, each of which can be updated independently when the
2855 model changes, without having to redraw the page. Instead of digging into
2856 a JSON object, looking up an element in the DOM, and updating the HTML by hand,
2857 you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
2858 event &mdash; and now everywhere that
2859 model data is displayed in the UI, it is always immediately up to date.
2860 </p>
2861
2862 <p id="View-extend">
2863 <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
2864 <br />
2865 Get started with views by creating a custom view class. You'll want to
2866 override the <a href="#View-render">render</a> function, specify your
2867 declarative <a href="#View-delegateEvents">events</a>, and perhaps the
2868 <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
2869 element.
2870 </p>
2871
2872 <pre>
2873 var DocumentRow = Backbone.View.extend({
2874
2875 tagName: "li",
2876
2877 className: "document-row",
2878
2879 events: {
2880 "click .icon": "open",
2881 "click .button.edit": "openEditDialog",
2882 "click .button.delete": "destroy"
2883 },
2884
2885 initialize: function() {
2886 this.listenTo(this.model, "change", this.render);
2887 },
2888
2889 render: function() {
2890 ...
2891 }
2892
2893 });
2894 </pre>
2895
2896 <p>
2897 Properties like <tt>tagName</tt>, <tt>id</tt>, <tt>className</tt>,
2898 <tt>el</tt>, and <tt>events</tt> may also be defined as a function, if
2899 you want to wait to define them until runtime.
2900 </p>
2901
2902 <p id="View-preinitialize">
2903 <b class="header">preinitialize</b><code>new View([options])</code>
2904 <br />
2905 For use with views as ES classes. If you define a <b>preinitialize</b>
2906 method, it will be invoked when the view is first created, before any
2907 instantiation logic is run.
2908 </p>
2909
2910 <pre>
2911 class Document extends Backbone.View {
2912 preinitialize({autoRender}) {
2913 this.autoRender = autoRender;
2914 }
2915
2916 initialize() {
2917 if (this.autoRender) {
2918 this.listenTo(this.model, "change", this.render);
2919 }
2920 }
2921 }
2922 </pre>
2923
2924 <p id="View-constructor">
2925 <b class="header">constructor / initialize</b><code>new View([options])</code>
2926 <br />
2927 There are several special
2928 options that, if passed, will be attached directly to the view:
2929 <tt>model</tt>, <tt>collection</tt>,
2930 <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, <tt>tagName</tt>, <tt>attributes</tt> and <tt>events</tt>.
2931 If the view defines an <b>initialize</b> function, it will be called when
2932 the view is first created. If you'd like to create a view that references
2933 an element <i>already</i> in the DOM, pass in the element as an option:
2934 <tt>new View({el: existingElement})</tt>
2935 </p>
2936
2937 <pre>
2938 var doc = documents.first();
2939
2940 new DocumentRow({
2941 model: doc,
2942 id: "document-row-" + doc.id
2943 });
2944 </pre>
2945
2946 <p id="View-el">
2947 <b class="header">el</b><code>view.el</code>
2948 <br />
2949 All views have a DOM element at all times (the <b>el</b> property),
2950 whether they've already been inserted into the page or not. In this
2951 fashion, views can be rendered at any time, and inserted into the DOM all
2952 at once, in order to get high-performance UI rendering with as few
2953 reflows and repaints as possible.
2954 </p>
2955
2956 <p>
2957 <tt>this.el</tt> can be resolved from a DOM selector string or an Element;
2958 otherwise it will be created from the view's <tt>tagName</tt>, <tt>className</tt>,
2959 <tt>id</tt> and <a href="#View-attributes"><tt>attributes</tt></a> properties.
2960 If none are set, <tt>this.el</tt> is an empty <tt>div</tt>, which is often just
2961 fine. An <b>el</b> reference may also be passed in to the view's constructor.
2962 </p>
2963
2964 <pre class="runnable">
2965 var ItemView = Backbone.View.extend({
2966 tagName: 'li'
2967 });
2968
2969 var BodyView = Backbone.View.extend({
2970 el: 'body'
2971 });
2972
2973 var item = new ItemView();
2974 var body = new BodyView();
2975
2976 alert(item.el + ' ' + body.el);
2977 </pre>
2978
2979 <p id="View-$el">
2980 <b class="header">$el</b><code>view.$el</code>
2981 <br />
2982 A cached jQuery object for the view's element. A handy
2983 reference instead of re-wrapping the DOM element all the time.
2984 </p>
2985
2986 <pre>
2987 view.$el.show();
2988
2989 listView.$el.append(itemView.el);
2990 </pre>
2991
2992 <p id="View-setElement">
2993 <b class="header">setElement</b><code>view.setElement(element)</code>
2994 <br />
2995 If you'd like to apply a Backbone view to a different DOM element, use
2996 <b>setElement</b>, which will also create the cached <tt>$el</tt> reference
2997 and move the view's delegated events from the old element to the new one.
2998 </p>
2999
3000 <p id="View-attributes">
3001 <b class="header">attributes</b><code>view.attributes</code>
3002 <br />
3003 A hash of attributes that will be set as HTML DOM element attributes on the
3004 view's <tt>el</tt> (id, class, data-properties, etc.), or a function that
3005 returns such a hash.
3006 </p>
3007
3008 <p id="View-dollar">
3009 <b class="header">$ (jQuery)</b><code>view.$(selector)</code>
3010 <br />
3011 If jQuery is included on the page, each view has a
3012 <b>$</b> function that runs queries scoped within the view's element. If you use this
3013 scoped jQuery function, you don't have to use model ids as part of your query
3014 to pull out specific elements in a list, and can rely much more on HTML class
3015 attributes. It's equivalent to running: <tt>view.$el.find(selector)</tt>
3016 </p>
3017
3018 <pre>
3019 ui.Chapter = Backbone.View.extend({
3020 serialize : function() {
3021 return {
3022 title: this.$(".title").text(),
3023 start: this.$(".start-page").text(),
3024 end: this.$(".end-page").text()
3025 };
3026 }
3027 });
3028 </pre>
3029
3030 <p id="View-template">
3031 <b class="header">template</b><code>view.template([data])</code>
3032 <br />
3033 While templating for a view isn't a function provided directly by Backbone,
3034 it's often a nice convention to define a <b>template</b> function on your
3035 views. In this way, when rendering your view, you have convenient access to
3036 instance data.
3037 For example, using Underscore templates:
3038 </p>
3039
3040 <pre>
3041 var LibraryView = Backbone.View.extend({
3042 template: _.template(...)
3043 });
3044 </pre>
3045
3046 <p id="View-render">
3047 <b class="header">render</b><code>view.render()</code>
3048 <br />
3049 The default implementation of <b>render</b> is a no-op. Override this
3050 function with your code that renders the view template from model data,
3051 and updates <tt>this.el</tt> with the new HTML. A good
3052 convention is to <tt>return this</tt> at the end of <b>render</b> to
3053 enable chained calls.
3054 </p>
3055
3056 <pre>
3057 var Bookmark = Backbone.View.extend({
3058 template: _.template(...),
3059 render: function() {
3060 this.$el.html(this.template(this.model.attributes));
3061 return this;
3062 }
3063 });
3064 </pre>
3065
3066 <p>
3067 Backbone is agnostic with respect to your preferred method of HTML templating.
3068 Your <b>render</b> function could even munge together an HTML string, or use
3069 <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
3070 choosing a nice JavaScript templating library.
3071 <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
3072 <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
3073 <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
3074 Because <a href="http://underscorejs.org/">Underscore.js</a> is already on the page,
3075 <a href="http://underscorejs.org/#template">_.template</a>
3076 is available, and is an excellent choice if you prefer simple
3077 interpolated-JavaScript style templates.
3078 </p>
3079
3080 <p>
3081 Whatever templating strategy you end up with, it's nice if you <i>never</i>
3082 have to put strings of HTML in your JavaScript. At DocumentCloud, we
3083 use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
3084 to package up JavaScript templates stored in <tt>/app/views</tt> as part
3085 of our main <tt>core.js</tt> asset package.
3086 </p>
3087
3088 <p id="View-remove">
3089 <b class="header">remove</b><code>view.remove()</code>
3090 <br />
3091 Removes a view and its <tt>el</tt> from the DOM, and calls
3092 <a href="#Events-stopListening">stopListening</a> to remove any bound
3093 events that the view has <a href="#Events-listenTo">listenTo</a>'d.
3094 </p>
3095
3096 <p id="View-events">
3097 <b class="header">events</b><code>view.events or view.events()</code>
3098 <br />
3099 The <b>events</b> hash (or method) can be used to specify a set of DOM
3100 events that will be bound to methods on your View
3101 through <a href="#View-delegateEvents">delegateEvents</a>.
3102 </p>
3103
3104 <p>
3105 Backbone will automatically attach the event listeners at instantiation
3106 time, right before invoking <a href="#View-constructor">initialize</a>.
3107 </p>
3108
3109 <pre>
3110 var ENTER_KEY = 13;
3111 var InputView = Backbone.View.extend({
3112
3113 tagName: 'input',
3114
3115 events: {
3116 "keydown" : "keyAction",
3117 },
3118
3119 render: function() { ... },
3120
3121 keyAction: function(e) {
3122 if (e.which === ENTER_KEY) {
3123 this.collection.add({text: this.$el.val()});
3124 }
3125 }
3126 });
3127 </pre>
3128
3129 <p id="View-delegateEvents">
3130 <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
3131 <br />
3132 Uses jQuery's <tt>on</tt> function to provide declarative callbacks
3133 for DOM events within a view.
3134 If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
3135 as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
3136 The callback may be either the name of a method on the view, or a direct
3137 function body.
3138 Omitting the <tt>selector</tt> causes the event to be bound to the view's
3139 root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
3140 within the View's constructor for you, so if you have a simple <tt>events</tt>
3141 hash, all of your DOM events will always already be connected, and you will
3142 never have to call this function yourself.
3143 </p>
3144
3145 <p>
3146 The <tt>events</tt> property may also be defined as a function that returns
3147 an <b>events</b> hash, to make it easier to programmatically define your
3148 events, as well as inherit them from parent views.
3149 </p>
3150
3151 <p>
3152 Using <b>delegateEvents</b> provides a number of advantages over manually
3153 using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
3154 callbacks are bound to the view before being handed off to jQuery, so when
3155 the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
3156 <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
3157 hash, all callbacks are removed and delegated afresh &mdash; useful for
3158 views which need to behave differently when in different modes.
3159 </p>
3160
3161 <p>
3162 A single-event version of <b>delegateEvents</b> is available as <tt>delegate</tt>.
3163 In fact, <b>delegateEvents</b> is simply a multi-event wrapper around <tt>delegate</tt>.
3164 A counterpart to <tt>undelegateEvents</tt> is available as <tt>undelegate</tt>.
3165 </p>
3166
3167 <p>
3168 A view that displays a document in a search result might look
3169 something like this:
3170 </p>
3171
3172 <pre>
3173 var DocumentView = Backbone.View.extend({
3174
3175 events: {
3176 "dblclick" : "open",
3177 "click .icon.doc" : "select",
3178 "contextmenu .icon.doc" : "showMenu",
3179 "click .show_notes" : "toggleNotes",
3180 "click .title .lock" : "editAccessLevel",
3181 "mouseover .title .date" : "showTooltip"
3182 },
3183
3184 render: function() {
3185 this.$el.html(this.template(this.model.attributes));
3186 return this;
3187 },
3188
3189 open: function() {
3190 window.open(this.model.get("viewer_url"));
3191 },
3192
3193 select: function() {
3194 this.model.set({selected: true});
3195 },
3196
3197 ...
3198
3199 });
3200 </pre>
3201
3202 <p id="View-undelegateEvents">
3203 <b class="header">undelegateEvents</b><code>undelegateEvents()</code>
3204 <br />
3205 Removes all of the view's delegated events. Useful if you want to disable
3206 or remove a view from the DOM temporarily.
3207 </p>
3208
3209 <h2 id="Utility">Utility</h2>
3210
3211 <p id="Utility-Backbone-noConflict">
3212 <b class="header">Backbone.noConflict</b><code>var backbone = Backbone.noConflict();</code>
3213 <br />
3214 Returns the <tt>Backbone</tt> object back to its original value. You can
3215 use the return value of <tt>Backbone.noConflict()</tt> to keep a local
3216 reference to Backbone. Useful for embedding Backbone on third-party
3217 websites, where you don't want to clobber the existing Backbone.
3218 </p>
3219
3220 <pre>
3221 var localBackbone = Backbone.noConflict();
3222 var model = localBackbone.Model.extend(...);
3223 </pre>
3224
3225 <p id="Utility-Backbone-$">
3226 <b class="header">Backbone.$</b><code>Backbone.$ = $;</code>
3227 <br />
3228 If you have multiple copies of <tt>jQuery</tt> on the page, or simply want
3229 to tell Backbone to use a particular object as its DOM / Ajax library,
3230 this is the property for you.
3231 </p>
3232
3233 <pre>
3234 Backbone.$ = require('jquery');
3235 </pre>
3236
3237 <h2 id="faq">F.A.Q.</h2>
3238
3239 <p id="FAQ-why-backbone">
3240 <b class="header">Why use Backbone, not [other framework X]?</b>
3241 <br />
3242 If your eye hasn't already been caught by the adaptability and elan on display
3243 in the above <a href="#examples">list of examples</a>, we can get more specific:
3244 Backbone.js aims to provide the common foundation that data-rich web applications
3245 with ambitious interfaces require &mdash; while very deliberately avoiding
3246 painting you into a corner by making any decisions that you're
3247 better equipped to make yourself.
3248 </p>
3249
3250 <ul>
3251 <li>
3252 The focus is on supplying you with
3253 <a href="#Collection-Underscore-Methods">helpful methods to manipulate and
3254 query your data</a>, not on HTML widgets or reinventing the JavaScript
3255 object model.
3256 </li>
3257 <li>
3258 Backbone does not force you to use a single template engine. Views can bind
3259 to HTML constructed in
3260 <a href="http://underscorejs.org/#template">your</a>
3261 <a href="http://guides.rubyonrails.org/layouts_and_rendering.html">favorite</a>
3262 <a href="http://mustache.github.com">way</a>.
3263 </li>
3264 <li>
3265 It's smaller. There are fewer kilobytes for your browser or phone to download,
3266 and less <i>conceptual</i> surface area. You can read and understand
3267 the source in an afternoon.
3268 </li>
3269 <li>
3270 It doesn't depend on stuffing application logic into your HTML.
3271 There's no embedded JavaScript, template logic, or binding hookup code in
3272 <tt>data-</tt> or <tt>ng-</tt> attributes, and no need to invent your own HTML tags.
3273 </li>
3274 <li>
3275 <a href="#Events">Synchronous events</a> are used as the fundamental
3276 building block, not a difficult-to-reason-about run loop, or by constantly
3277 polling and traversing your data structures to hunt for changes. And if
3278 you want a specific event to be asynchronous and aggregated,
3279 <a href="http://underscorejs.org/#debounce">no problem</a>.
3280 </li>
3281 <li>
3282 Backbone scales well, from <a href="http://disqus.com">embedded widgets</a>
3283 to <a href="http://www.usatoday.com">massive apps</a>.
3284 </li>
3285 <li>
3286 Backbone is a library, not a framework, and plays well with others.
3287 You can embed Backbone widgets in Dojo apps without trouble, or use Backbone
3288 models as the data backing for D3 visualizations (to pick two entirely
3289 random examples).
3290 </li>
3291 <li>
3292 "Two-way data-binding" is avoided. While it certainly makes for a nifty
3293 demo, and works for the most basic CRUD, it doesn't tend to be terribly
3294 useful in your real-world app. Sometimes you want to update on
3295 every keypress, sometimes on blur, sometimes when the panel is closed,
3296 and sometimes when the "save" button is clicked. In almost all cases, simply
3297 serializing the form to JSON is faster and easier. All that aside, if your
3298 heart is set, <a href="http://rivetsjs.com">go</a>
3299 <a href="http://nytimes.github.com/backbone.stickit/">for it</a>.
3300 </li>
3301 <li>
3302 There's no built-in performance penalty for choosing to structure your
3303 code with Backbone. And if you do want to optimize further, thin models and
3304 templates with flexible granularity make it easy to squeeze every last
3305 drop of potential performance out of, say, IE8.
3306 </li>
3307 </ul>
3308
3309 <p id="FAQ-tim-toady">
3310 <b class="header">There's More Than One Way To Do It</b>
3311 <br />
3312 It's common for folks just getting started to treat the examples listed
3313 on this page as some sort of gospel truth. In fact, Backbone.js is intended
3314 to be fairly agnostic about many common patterns in client-side code.
3315 For example...
3316 </p>
3317
3318 <p>
3319 <b>References between Models and Views</b> can be handled several ways.
3320 Some people like to have direct pointers, where views correspond 1:1 with
3321 models (<tt>model.view</tt> and <tt>view.model</tt>). Others prefer to have intermediate
3322 "controller" objects that orchestrate the creation and organization of
3323 views into a hierarchy. Others still prefer the evented approach, and always
3324 fire events instead of calling methods directly. All of these styles work well.
3325 </p>
3326
3327 <p>
3328 <b>Batch operations</b> on Models are common, but often best handled differently
3329 depending on your server-side setup. Some folks don't mind making individual
3330 Ajax requests. Others create explicit resources for RESTful batch operations:
3331 <tt>/notes/batch/destroy?ids=1,2,3,4</tt>. Others tunnel REST over JSON, with the
3332 creation of "changeset" requests:
3333 </p>
3334
3335 <pre>
3336 {
3337 "create": [array of models to create]
3338 "update": [array of models to update]
3339 "destroy": [array of model ids to destroy]
3340 }
3341 </pre>
3342
3343 <p>
3344 <b>Feel free to define your own events.</b> <a href="#Events">Backbone.Events</a>
3345 is designed so that you can mix it in to any JavaScript object or prototype.
3346 Since you can use any string as an event, it's often handy to bind
3347 and trigger your own custom events: <tt>model.on("selected:true")</tt> or
3348 <tt>model.on("editing")</tt>
3349 </p>
3350
3351 <p>
3352 <b>Render the UI</b> as you see fit. Backbone is agnostic as to whether you
3353 use <a href="http://underscorejs.org/#template">Underscore templates</a>,
3354 <a href="https://github.com/janl/mustache.js">Mustache.js</a>, direct DOM
3355 manipulation, server-side rendered snippets of HTML, or
3356 <a href="http://jqueryui.com/">jQuery UI</a> in your <tt>render</tt> function.
3357 Sometimes you'll create a view for each model ... sometimes you'll have a
3358 view that renders thousands of models at once, in a tight loop. Both can be
3359 appropriate in the same app, depending on the quantity of data involved,
3360 and the complexity of the UI.
3361 </p>
3362
3363 <p id="FAQ-nested">
3364 <b class="header">Nested Models &amp; Collections</b>
3365 <br />
3366 It's common to nest collections inside of models with Backbone. For example,
3367 consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
3368 One nice pattern for handling this is have a <tt>this.messages</tt> collection
3369 for each mailbox, enabling the lazy-loading of messages, when the mailbox
3370 is first opened ... perhaps with <tt>MessageList</tt> views listening for
3371 <tt>"add"</tt> and <tt>"remove"</tt> events.
3372 </p>
3373
3374 <pre>
3375 var Mailbox = Backbone.Model.extend({
3376
3377 initialize: function() {
3378 this.messages = new Messages;
3379 this.messages.url = '/mailbox/' + this.id + '/messages';
3380 this.messages.on("reset", this.updateCounts);
3381 },
3382
3383 ...
3384
3385 });
3386
3387 var inbox = new Mailbox;
3388
3389 // And then, when the Inbox is opened:
3390
3391 inbox.messages.fetch({reset: true});
3392 </pre>
3393
3394 <p>
3395 If you're looking for something more opinionated, there are a number of
3396 Backbone plugins that add sophisticated associations among models,
3397 <a href="https://github.com/jashkenas/backbone/wiki/Extensions%2C-Plugins%2C-Resources">available on the wiki</a>.
3398 </p>
3399
3400 <p>
3401 Backbone doesn't include direct support for nested models and collections
3402 or "has many" associations because there are a number
3403 of good patterns for modeling structured data on the client side, and
3404 <i>Backbone should provide the foundation for implementing any of them.</i>
3405 You may want to&hellip;
3406 </p>
3407
3408 <ul>
3409 <li>
3410 Mirror an SQL database's structure, or the structure of a NoSQL database.
3411 </li>
3412 <li>
3413 Use models with arrays of "foreign key" ids, and join to top level
3414 collections (a-la tables).
3415 </li>
3416 <li>
3417 For associations that are numerous, use a range of ids instead of an
3418 explicit list.
3419 </li>
3420 <li>
3421 Avoid ids, and use direct references, creating a partial object graph
3422 representing your data set.
3423 </li>
3424 <li>
3425 Lazily load joined models from the server, or lazily deserialize nested
3426 models from JSON documents.
3427 </li>
3428 </ul>
3429
3430 <p id="FAQ-bootstrap">
3431 <b class="header">Loading Bootstrapped Models</b>
3432 <br />
3433 When your app first loads, it's common to have a set of initial models that
3434 you know you're going to need, in order to render the page. Instead of
3435 firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
3436 a nicer pattern is to have their data already bootstrapped into the page.
3437 You can then use <a href="#Collection-reset">reset</a> to populate your
3438 collections with the initial data. At DocumentCloud, in the
3439 <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
3440 workspace, we do something along these lines:
3441 </p>
3442
3443 <pre>
3444 &lt;script&gt;
3445 var accounts = new Backbone.Collection;
3446 accounts.reset(&lt;%= @accounts.to_json %&gt;);
3447 var projects = new Backbone.Collection;
3448 projects.reset(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
3449 &lt;/script&gt;
3450 </pre>
3451
3452 <p>You have to <a href="http://mathiasbynens.be/notes/etago">escape</a>
3453 <tt>&lt;/</tt> within the JSON string, to prevent JavaScript injection
3454 attacks.
3455
3456 <p id="FAQ-extending">
3457 <b class="header">Extending Backbone</b>
3458 <br />
3459 Many JavaScript libraries are meant to be insular and self-enclosed,
3460 where you interact with them by calling their public API, but never peek
3461 inside at the guts. Backbone.js is <i>not</i> that kind of library.
3462 </p>
3463
3464 <p>
3465 Because it serves as a foundation for your application, you're meant to
3466 extend and enhance it in the ways you see fit &mdash; the entire source
3467 code is <a href="docs/backbone.html">annotated</a> to make this easier
3468 for you. You'll find that there's very little there apart from core
3469 functions, and most of those can be overridden or augmented should you find
3470 the need. If you catch yourself adding methods to <tt>Backbone.Model.prototype</tt>,
3471 or creating your own base subclass, don't worry &mdash; that's how things are
3472 supposed to work.
3473 </p>
3474
3475 <p id="FAQ-mvc">
3476 <b class="header">How does Backbone relate to "traditional" MVC?</b>
3477 <br />
3478 Different implementations of the
3479 <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
3480 pattern tend to disagree about the definition of a controller. If it helps any, in
3481 Backbone, the <a href="#View">View</a> class can also be thought of as a
3482 kind of controller, dispatching events that originate from the UI, with
3483 the HTML template serving as the true view. We call it a View because it
3484 represents a logical chunk of UI, responsible for the contents of a single
3485 DOM element.
3486 </p>
3487
3488 <p>
3489 Comparing the overall structure of Backbone to a server-side MVC framework
3490 like <b>Rails</b>, the pieces line up like so:
3491 </p>
3492
3493 <ul>
3494 <li>
3495 <b>Backbone.Model</b> &ndash; Like a Rails model minus the class
3496 methods. Wraps a row of data in business logic.
3497 </li>
3498 <li>
3499 <b>Backbone.Collection</b> &ndash; A group of models on the client-side,
3500 with sorting/filtering/aggregation logic.
3501 </li>
3502 <li>
3503 <b>Backbone.Router</b> &ndash; Rails <tt>routes.rb</tt> + Rails controller
3504 actions. Maps URLs to functions.
3505 </li>
3506 <li>
3507 <b>Backbone.View</b> &ndash; A logical, re-usable piece of UI. Often,
3508 but not always, associated with a model.
3509 </li>
3510 <li>
3511 <b>Client-side Templates</b> &ndash; Rails <tt>.html.erb</tt> views,
3512 rendering a chunk of HTML.
3513 </li>
3514 </ul>
3515
3516 <p id="FAQ-this">
3517 <b class="header">Binding "this"</b>
3518 <br />
3519 Perhaps the single most common JavaScript "gotcha" is the fact that when
3520 you pass a function as a callback, its value for <tt>this</tt> is lost.
3521 When dealing with <a href="#Events">events</a> and callbacks in Backbone,
3522 you'll often find it useful to rely on <a href="#Events-listenTo">listenTo</a>
3523 or the optional <tt>context</tt> argument that many of Underscore
3524 and Backbone's methods use to specify the <tt>this</tt>
3525 that will be used when the callback is later invoked. (See
3526 <a href="http://underscorejs.org/#each">_.each</a>,
3527 <a href="http://underscorejs.org/#map">_.map</a>, and
3528 <a href="#Events-on">object.on</a>, to name a few).
3529 <a href="#View-delegateEvents">View events</a> are automatically bound to
3530 the view's context for you.
3531 You may also find it helpful to use
3532 <a href="http://underscorejs.org/#bind">_.bind</a> and
3533 <a href="http://underscorejs.org/#bindAll">_.bindAll</a>
3534 from Underscore.js.
3535 </p>
3536
3537 <pre>
3538 var MessageList = Backbone.View.extend({
3539
3540 initialize: function() {
3541 var messages = this.collection;
3542 messages.on("reset", this.render, this);
3543 messages.on("add", this.addMessage, this);
3544 messages.on("remove", this.removeMessage, this);
3545
3546 messsages.each(this.addMessage, this);
3547 }
3548
3549 });
3550
3551 // Later, in the app...
3552
3553 Inbox.messages.add(newMessage);
3554 </pre>
3555
3556 <p id="FAQ-rails">
3557 <b class="header">Working with Rails</b>
3558 <br />
3559 Backbone.js was originally extracted from
3560 <a href="http://www.documentcloud.org">a Rails application</a>; getting
3561 your client-side (Backbone) Models to sync correctly with your server-side
3562 (Rails) Models is painless, but there are still a few things to be aware of.
3563 </p>
3564
3565 <p>
3566 By default, Rails versions prior to 3.1 add an extra layer of wrapping
3567 around the JSON representation of models. You can disable this wrapping
3568 by setting:
3569 </p>
3570
3571 <pre>
3572 ActiveRecord::Base.include_root_in_json = false
3573 </pre>
3574
3575 <p>
3576 ... in your configuration. Otherwise, override
3577 <a href="#Model-parse">parse</a> to pull model attributes out of the
3578 wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations
3579 of models, where by default Rails expects namespaced attributes. You can
3580 have your controllers filter attributes directly from <tt>params</tt>, or
3581 you can override <a href="#Model-toJSON">toJSON</a> in Backbone to add
3582 the extra wrapping Rails expects.
3583 </p>
3584
3585 <h2 id="examples">Examples</h2>
3586
3587 <p>
3588 The list of examples that follows, while long, is not exhaustive — nor in
3589 any way current. If you've worked on an app that uses Backbone, please
3590 add it to the <a href="https://github.com/jashkenas/backbone/wiki/Projects-and-Companies-using-Backbone">wiki page of Backbone apps</a>.
3591 </p>
3592
3593 <p id="examples-todos">
3594 <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
3595 <a href="examples/todos/index.html">Todo List application</a>
3596 that is bundled in the repository as Backbone example. If you're wondering
3597 where to get started with Backbone in general, take a moment to
3598 <a href="docs/examples/todos/todos.html">read through the annotated source</a>. The app uses a
3599 <a href="http://github.com/jeromegn/Backbone.localStorage">LocalStorage adapter</a>
3600 to transparently save all of your todos within your browser, instead of
3601 sending them to a server. Jérôme also has a version hosted at
3602 <a href="http://localtodos.com/">localtodos.com</a>.
3603 </p>
3604
3605 <div style="text-align: center;">
3606 <a href="examples/todos/index.html">
3607 <img width="400" height="427" data-original="docs/images/todos.jpg" alt="Todos" class="example_retina" />
3608 </a>
3609 </div>
3610
3611 <h2 id="examples-documentcloud">DocumentCloud</h2>
3612
3613 <p>
3614 The <a href="http://www.documentcloud.org/public/#search/">DocumentCloud workspace</a>
3615 is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
3616 <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
3617 If you're interested in history &mdash; both Underscore.js and Backbone.js
3618 were originally extracted from the DocumentCloud codebase, and packaged
3619 into standalone JS libraries.
3620 </p>
3621
3622 <div style="text-align: center;">
3623 <a href="http://www.documentcloud.org/public/#search/">
3624 <img width="550" height="453" data-original="docs/images/dc-workspace.jpg" alt="DocumentCloud Workspace" class="example_retina" />
3625 </a>
3626 </div>
3627
3628 <h2 id="examples-usa-today">USA Today</h2>
3629
3630 <p>
3631 <a href="http://usatoday.com">USA Today</a> takes advantage of the modularity of
3632 Backbone's data/model lifecycle &mdash; which makes it simple to create, inherit,
3633 isolate, and link application objects &mdash; to keep the codebase both manageable and efficient.
3634 The new website also makes heavy use of the Backbone Router to control the
3635 page for both pushState-capable and legacy browsers.
3636 Finally, the team took advantage of Backbone's Event module to create a
3637 PubSub API that allows third parties and analytics packages to hook into the
3638 heart of the app.
3639 </p>
3640
3641 <div style="text-align: center;">
3642 <a href="http://usatoday.com">
3643 <img width="550" height="532" data-original="docs/images/usa-today.jpg" alt="USA Today" class="example_retina" />
3644 </a>
3645 </div>
3646
3647 <h2 id="examples-rdio">Rdio</h2>
3648
3649 <p>
3650 <a href="http://rdio.com/new">New Rdio</a> was developed from the ground
3651 up with a component based framework based on Backbone.js. Every component
3652 on the screen is dynamically loaded and rendered, with data provided by the
3653 <a href="http://developer.rdio.com/">Rdio API</a>. When changes are pushed,
3654 every component can update itself without reloading the page or interrupting
3655 the user's music. All of this relies on Backbone's views and models,
3656 and all URL routing is handled by Backbone's Router. When data changes are
3657 signaled in realtime, Backbone's Events notify the interested components
3658 in the data changes. Backbone forms the core of the new, dynamic, realtime
3659 Rdio web and <i>desktop</i> applications.
3660 </p>
3661
3662 <div style="text-align: center;">
3663 <a href="http://rdio.com/new">
3664 <img width="550" height="344" data-original="docs/images/rdio.jpg" alt="Rdio" class="example_retina" />
3665 </a>
3666 </div>
3667
3668 <h2 id="examples-hulu">Hulu</h2>
3669
3670 <p>
3671 <a href="http://hulu.com">Hulu</a> used Backbone.js to build its next
3672 generation online video experience. With Backbone as a foundation, the
3673 web interface was rewritten from scratch so that all page content can
3674 be loaded dynamically with smooth transitions as you navigate.
3675 Backbone makes it easy to move through the app quickly without the
3676 reloading of scripts and embedded videos, while also offering models and
3677 collections for additional data manipulation support.
3678 </p>
3679
3680 <div style="text-align: center;">
3681 <a href="http://hulu.com">
3682 <img width="550" height="449" data-original="docs/images/hulu.jpg" alt="Hulu" class="example_retina" />
3683 </a>
3684 </div>
3685
3686 <h2 id="examples-quartz">Quartz</h2>
3687
3688 <p>
3689 <a href="http://qz.com">Quartz</a> sees itself as a digitally native news
3690 outlet for the new
3691 global economy. Because Quartz believes in the future of open,
3692 cross-platform web applications, they selected Backbone and Underscore
3693 to fetch, sort, store, and display content from a custom WordPress
3694 API. Although <a href="http://qz.com">qz.com</a> uses responsive design
3695 for phone, tablet, and
3696 desktop browsers, it also takes advantage of Backbone events and views
3697 to render device-specific templates in some cases.
3698 </p>
3699
3700 <div style="text-align: center;">
3701 <a href="http://qz.com">
3702 <img width="510" height="360" data-original="docs/images/quartz.jpg" alt="Quartz" class="example_retina" />
3703 </a>
3704 </div>
3705
3706 <h2 id="examples-earth">Earth</h2>
3707
3708 <p>
3709 <a href="http://earth.nullschool.net">Earth.nullschool.net</a> displays real-time weather
3710 conditions on an interactive animated globe, and Backbone provides the
3711 foundation upon which all of the site's components are built. Despite the
3712 presence of several other JavaScript libraries, Backbone's non-opinionated
3713 design made it effortless to mix-in the <a href="#Events">Events</a> functionality used for
3714 distributing state changes throughout the page. When the decision was made
3715 to switch to Backbone, large blocks of custom logic simply disappeared.
3716 </p>
3717
3718 <div style="text-align: center;">
3719 <a href="http://earth.nullschool.net">
3720 <img width="545" height="583" data-original="docs/images/earth.jpg" alt="Earth" class="example_retina" />
3721 </a>
3722 </div>
3723
3724 <h2 id="examples-vox">Vox</h2>
3725
3726 <p>
3727 Vox Media, the publisher of
3728 <a href="http://www.sbnation.com/">SB Nation</a>,
3729 <a href="http://www.theverge.com/">The Verge</a>,
3730 <a href="http://www.polygon.com/">Polygon</a>,
3731 <a href="http://www.eater.com/">Eater</a>,
3732 <a href="http://www.racked.com/">Racked</a>,
3733 <a href="http://www.curbed.com/">Curbed</a>, and
3734 <a href="http://www.vox.com/">Vox.com</a>, uses Backbone throughout
3735 <a href="http://techcrunch.com/2012/05/07/a-closer-look-at-chorus-the-next-generation-publishing-platform-that-runs-vox-media/">Chorus</a>,
3736 its home-grown publishing platform. Backbone powers the
3737 <a href="http://product.voxmedia.com/post/25113965826/introducing-syllabus-vox-medias-s3-powered-liveblog">liveblogging platform</a>
3738 and <a href="http://product.voxmedia.com/2013/11/11/5426878/using-backbone-js-for-sanity-and-stability">commenting system</a>
3739 used across all Vox Media properties; Coverage, an internal editorial coordination tool;
3740 <a href="http://www.sbnation.com/college-basketball/2014/4/7/5592112/kentucky-vs-uconn-2014-ncaa-tournament-championship-live-chat">SB Nation Live</a>,
3741 a live event coverage and chat tool; and
3742 <a href="http://www.vox.com/cards/ukraine-everything-you-need-to-know/what-is-the-ukraine-crisis">Vox Cards</a>,
3743 Vox.com's highlighter-and-index-card inspired app for providing context about the news.
3744 </p>
3745
3746 <div style="text-align: center;">
3747 <a href="http://vox.com">
3748 <img width="550" height="402" data-original="docs/images/vox.jpg" alt="Vox" class="example_retina" />
3749 </a>
3750 </div>
3751
3752 <h2 id="examples-gawker">Gawker Media</h2>
3753
3754 <p>
3755 <a href="http://kinja.com">Kinja</a> is Gawker Media's publishing platform designed
3756 to create great stories by breaking down the lines between the traditional
3757 roles of content creators and consumers. Everyone — editors, readers,
3758 marketers — have access to the same tools to engage in passionate discussion
3759 and pursue the truth of the story. Sharing, recommending, and following within the
3760 Kinja ecosystem allows for improved information discovery across all the sites.
3761 </p>
3762 <p>
3763 Kinja is the platform behind
3764 <a href="http://gawker.com/">Gawker</a>,
3765 <a href="http://gizmodo.com/">Gizmodo</a>,
3766 <a href="http://lifehacker.com/">Lifehacker</a>,
3767 <a href="http://io9.com/">io9</a> and other Gawker Media
3768 blogs. Backbone.js underlies the front-end application code that powers
3769 everything from user authentication to post authoring, commenting, and even serving
3770 ads. The JavaScript stack includes
3771 <a href="http://underscorejs.org/">Underscore.js</a> and
3772 <a href="http://jquery.com/">jQuery</a>, with some plugins,
3773 all loaded with
3774 <a href="http://requirejs.org/">RequireJS</a>. Closure templates are shared between the
3775 <a href="http://www.playframework.com/">Play! Framework</a> based Scala application and Backbone views, and the responsive layout
3776 is done with the
3777 <a href="http://foundation.zurb.com/">Foundation</a> framework using
3778 <a href="http://sass-lang.com/">SASS</a>.
3779 </p>
3780
3781 <div style="text-align: center;">
3782 <a href="http://gawker.com">
3783 <img width="558" height="473" data-original="docs/images/gawker.jpg" alt="Gawker" class="example_retina" />
3784 </a>
3785 </div>
3786
3787 <h2 id="examples-flow">Flow</h2>
3788
3789 <p>
3790 <a href="http://www.metalabdesign.com/">MetaLab</a> used Backbone.js to create
3791 <a href="http://www.getflow.com/">Flow</a>, a task management app for teams. The
3792 workspace relies on Backbone.js to construct task views, activities, accounts,
3793 folders, projects, and tags. You can see the internals under <tt>window.Flow</tt>.
3794 </p>
3795
3796 <div style="text-align: center;">
3797 <a href="http://www.getflow.com/">
3798 <img width="550" height="416" data-original="docs/images/flow.jpg" alt="Flow" class="example_retina" />
3799 </a>
3800 </div>
3801
3802 <h2 id="examples-gilt">Gilt Groupe</h2>
3803
3804 <p>
3805 <a href="http://gilt.com">Gilt Groupe</a> uses Backbone.js to build multiple
3806 applications across their family of sites.
3807 <a href="http://m.gilt.com">Gilt's mobile website</a> uses Backbone and
3808 <a href="http://zeptojs.com">Zepto.js</a> to create a blazing-fast
3809 shopping experience for users on-the-go, while
3810 <a href="http://live.gilt.com">Gilt Live</a> combines Backbone with
3811 WebSockets to display the items that customers are buying in real-time. Gilt's search
3812 functionality also uses Backbone to filter and sort products efficiently
3813 by moving those actions to the client-side.
3814 </p>
3815
3816 <div style="text-align: center;">
3817 <a href="http://www.gilt.com/">
3818 <img width="550" height="444" data-original="docs/images/gilt.jpg" alt="Gilt Groupe" class="example_retina" />
3819 </a>
3820 </div>
3821
3822 <h2 id="examples-enigma">Enigma</h2>
3823
3824 <p>
3825 <a href="http://enigma.io">Enigma</a> is a portal amassing the largest
3826 collection of public data produced by governments, universities, companies,
3827 and organizations. Enigma uses Backbone Models and Collections to represent
3828 complex data structures; and Backbone's Router gives Enigma users unique URLs for
3829 application states, allowing them to navigate quickly through the site while
3830 maintaining the ability to bookmark pages and navigate forward and backward
3831 through their session.
3832 </p>
3833
3834 <div style="text-align: center;">
3835 <a href="http://www.enigma.io/">
3836 <img width="550" height="409" data-original="docs/images/enigma.jpg" alt="Enigma" class="example_retina" />
3837 </a>
3838 </div>
3839
3840 <h2 id="examples-newsblur">NewsBlur</h2>
3841
3842 <p>
3843 <a href="http://www.newsblur.com">NewsBlur</a> is an RSS feed reader and
3844 social news network with a fast and responsive UI that feels like a
3845 native desktop app. Backbone.js was selected for
3846 <a href="http://www.ofbrooklyn.com/2012/11/13/backbonification-migrating-javascript-to-backbone/">a major rewrite and transition from spaghetti code</a>
3847 because of its powerful yet simple feature set, easy integration, and large
3848 community. If you want to poke around under the hood, NewsBlur is also entirely
3849 <a href="http://github.com/samuelclay/NewsBlur">open-source</a>.
3850 </p>
3851
3852 <div style="text-align: center;">
3853 <a href="http://newsblur.com">
3854 <img width="510" height="340" data-original="docs/images/newsblur.jpg" alt="Newsblur" class="example_retina" />
3855 </a>
3856 </div>
3857
3858 <h2 id="examples-wordpress">WordPress.com</h2>
3859
3860 <p>
3861 <a href="http://wordpress.com/">WordPress.com</a> is the software-as-a-service
3862 version of <a href="http://wordpress.org">WordPress</a>. It uses Backbone.js
3863 Models, Collections, and Views in its
3864 <a href="http://en.blog.wordpress.com/2012/05/25/notifications-refreshed/">Notifications system</a>. Backbone.js was selected
3865 because it was easy to fit into the structure of the application, not the
3866 other way around. <a href="http://automattic.com">Automattic</a>
3867 (the company behind WordPress.com) is integrating Backbone.js into the
3868 Stats tab and other features throughout the homepage.
3869 </p>
3870
3871 <div style="text-align: center;">
3872 <a href="http://wordpress.com/">
3873 <img width="550" height="387" data-original="docs/images/wpcom-notifications.jpg" alt="WordPress.com Notifications"
3874 title="WordPress.com Notifications" class="example_retina" />
3875 </a>
3876 </div>
3877
3878 <h2 id="examples-foursquare">Foursquare</h2>
3879
3880 <p>
3881 Foursquare is a fun little startup that helps you meet up with friends,
3882 discover new places, and save money. Backbone Models are heavily used in
3883 the core JavaScript API layer and Views power many popular features like
3884 the <a href="https://foursquare.com">homepage map</a> and
3885 <a href="https://foursquare.com/seriouseats/list/the-best-doughnuts-in-ny">lists</a>.
3886 </p>
3887
3888 <div style="text-align: center;">
3889 <a href="http://foursquare.com">
3890 <img width="550" height="427" data-original="docs/images/foursquare.jpg" alt="Foursquare" class="example_retina" />
3891 </a>
3892 </div>
3893
3894 <h2 id="examples-bitbucket">Bitbucket</h2>
3895
3896 <p>
3897 <a href="http://www.bitbucket.org">Bitbucket</a> is a free source code hosting
3898 service for Git and Mercurial. Through its models and collections,
3899 Backbone.js has proved valuable in supporting Bitbucket's
3900 <a href="https://api.bitbucket.org">REST API</a>, as well as newer
3901 components such as in-line code comments and approvals for pull requests.
3902 Mustache templates provide server and client-side rendering, while a custom
3903 <a href="https://developers.google.com/closure/library/">Google Closure</a>
3904 inspired life-cycle for widgets allows Bitbucket to decorate existing DOM
3905 trees and insert new ones.
3906 </p>
3907
3908 <div style="text-align: center;">
3909 <a href="http://www.bitbucket.org">
3910 <img width="550" height="356" data-original="docs/images/bitbucket.jpg" alt="Bitbucket" class="example_retina" />
3911 </a>
3912 </div>
3913
3914 <h2 id="examples-disqus">Disqus</h2>
3915
3916 <p>
3917 <a href="http://www.disqus.com">Disqus</a> chose Backbone.js to power the
3918 latest version of their commenting widget. Backbone&rsquo;s small
3919 footprint and easy extensibility made it the right choice for Disqus&rsquo;
3920 distributed web application, which is hosted entirely inside an iframe and
3921 served on thousands of large web properties, including IGN, Wired, CNN, MLB, and more.
3922 </p>
3923
3924 <div style="text-align: center;">
3925 <a href="http://www.disqus.com">
3926 <img width="550" height="454" data-original="docs/images/disqus.jpg" alt="Disqus" class="example_retina" />
3927 </a>
3928 </div>
3929
3930 <h2 id="examples-delicious">Delicious</h2>
3931
3932 <p>
3933 <a href="https://delicious.com/">Delicious</a> is a social bookmarking
3934 platform making it easy to save, sort, and store bookmarks from across
3935 the web. Delicious uses <a href="http://chaplinjs.org">Chaplin.js</a>,
3936 Backbone.js and AppCache to build a full-featured MVC web app.
3937 The use of Backbone helped the website and
3938 <a href="http://delicious.com/tools">mobile apps</a> share a
3939 single API service, and the reuse of the model tier made it significantly
3940 easier to share code during the recent Delicious redesign.
3941 </p>
3942
3943 <div style="text-align: center;">
3944 <a href="http://www.delicious.com">
3945 <img width="510" height="321" data-original="docs/images/delicious.jpg" alt="Delicious" class="example_retina" />
3946 </a>
3947 </div>
3948
3949 <h2 id="examples-khan-academy">Khan Academy</h2>
3950
3951 <p>
3952 <a href="http://www.khanacademy.org">Khan Academy</a> is on a mission to
3953 provide a free world-class education to anyone anywhere. With thousands of
3954 videos, hundreds of JavaScript-driven exercises, and big plans for the
3955 future, Khan Academy uses Backbone to keep frontend code modular and organized.
3956 User profiles and goal setting are implemented with Backbone,
3957 <a href="http://jquery.com/">jQuery</a> and
3958 <a href="http://handlebarsjs.com/">Handlebars</a>, and most new feature
3959 work is being pushed to the client side, greatly increasing the quality of
3960 <a href="https://github.com/Khan/khan-api/">the API</a>.
3961 </p>
3962
3963 <div style="text-align: center;">
3964 <a href="http://www.khanacademy.org">
3965 <img width="550" height="454" data-original="docs/images/khan-academy.jpg" alt="Khan Academy" class="example_retina" />
3966 </a>
3967 </div>
3968
3969 <h2 id="examples-irccloud">IRCCloud</h2>
3970
3971 <p>
3972 <a href="http://irccloud.com/">IRCCloud</a>
3973 is an always-connected IRC client that you use in your
3974 browser &mdash; often leaving it open all day in a tab.
3975 The sleek web interface communicates with an
3976 Erlang backend via websockets and the
3977 <a href="https://github.com/irccloud/irccloud-tools/wiki/API-Overview">IRCCloud API</a>.
3978 It makes heavy use of Backbone.js events, models, views and routing to keep
3979 your IRC conversations flowing in real time.
3980 </p>
3981
3982 <div style="text-align: center;">
3983 <a href="http://irccloud.com/">
3984 <img width="550" height="392" data-original="docs/images/irccloud.png" alt="IRCCloud" class="example_image" />
3985 </a>
3986 </div>
3987
3988 <h2 id="examples-pitchfork">Pitchfork</h2>
3989
3990 <p>
3991 <a href="http://pitchfork.com/">Pitchfork</a> uses Backbone.js to power
3992 its site-wide audio player, <a href="http://pitchfork.com/tv/">Pitchfork.tv</a>,
3993 location routing, a write-thru page fragment cache, and more. Backbone.js
3994 (and <a href="http://underscorejs.org/">Underscore.js</a>) helps the team
3995 create clean and modular components,
3996 move very quickly, and focus on the site, not the spaghetti.
3997 </p>
3998
3999 <div style="text-align: center;">
4000 <a href="http://pitchfork.com/">
4001 <img width="550" height="428" data-original="docs/images/pitchfork.jpg" alt="Pitchfork" class="example_retina" />
4002 </a>
4003 </div>
4004
4005 <h2 id="examples-spin">Spin</h2>
4006
4007 <p>
4008 <a href="http://spin.com/">Spin</a> pulls in the
4009 <a href="http://www.spin.com/news">latest news stories</a> from
4010 their internal API onto their site using Backbone models and collections, and a
4011 custom <tt>sync</tt> method. Because the music should never stop playing,
4012 even as you click through to different "pages", Spin uses a Backbone router
4013 for navigation within the site.
4014 </p>
4015
4016 <div style="text-align: center;">
4017 <a href="http://spin.com/">
4018 <img width="550" height="543" data-original="docs/images/spin.jpg" alt="Spin" class="example_retina" />
4019 </a>
4020 </div>
4021
4022 <h2 id="examples-zocdoc">ZocDoc</h2>
4023
4024 <p>
4025 <a href="http://www.zocdoc.com">ZocDoc</a> helps patients
4026 find local, in-network doctors and dentists, see their real-time
4027 availability, and instantly book appointments.
4028 On the public side, the webapp uses Backbone.js to handle client-side state and rendering in
4029 <a href="http://www.zocdoc.com/primary-care-doctors/los-angeles-13122pm">search pages</a>
4030 and <a href="http://www.zocdoc.com/doctor/nathan-hashimoto-md-58078">doctor profiles</a>.
4031 In addition, the new version of the doctor-facing part of the website is a
4032 large single-page application that
4033 benefits from Backbone's structure and modularity. ZocDoc's Backbone
4034 classes are tested with
4035 <a href="https://jasmine.github.io/">Jasmine</a>, and delivered
4036 to the end user with
4037 <a href="http://getcassette.net/">Cassette</a>.
4038 </p>
4039
4040 <div style="text-align: center;">
4041 <a href="http://www.zocdoc.com">
4042 <img width="510" height="464" data-original="docs/images/zocdoc.jpg" alt="ZocDoc" class="example_retina" />
4043 </a>
4044 </div>
4045
4046 <h2 id="examples-walmart">Walmart Mobile</h2>
4047
4048 <p>
4049 <a href="http://www.walmart.com/">Walmart</a> used Backbone.js to create the new version
4050 of <a href="http://mobile.walmart.com/">their mobile web application</a> and
4051 created two new frameworks in the process.
4052 <a href="http://walmartlabs.github.com/thorax/">Thorax</a> provides mixins, inheritable
4053 events, as well as model and collection view bindings that integrate directly with
4054 <a href="http://handlebarsjs.com/">Handlebars</a> templates.
4055 <a href="http://walmartlabs.github.com/lumbar/">Lumbar</a> allows the application to be
4056 split into modules which can be loaded on demand, and creates platform specific builds
4057 for the portions of the web application that are embedded in Walmart's native Android
4058 and iOS applications.
4059 </p>
4060
4061 <div style="text-align: center;">
4062 <a href="http://mobile.walmart.com/r/phoenix">
4063 <img width="256" height="534" data-original="docs/images/walmart-mobile.png" alt="Walmart Mobile" class="example_image" />
4064 </a>
4065 </div>
4066
4067 <h2 id="examples-groupon">Groupon Now!</h2>
4068
4069 <p>
4070 <a href="http://www.groupon.com/now">Groupon Now!</a> helps you find
4071 local deals that you can buy and use right now. When first developing
4072 the product, the team decided it would be AJAX heavy with smooth transitions
4073 between sections instead of full refreshes, but still needed to be fully
4074 linkable and shareable. Despite never having used Backbone before, the
4075 learning curve was incredibly quick &mdash; a prototype was hacked out in an
4076 afternoon, and the team was able to ship the product in two weeks.
4077 Because the source is minimal and understandable, it was easy to
4078 add several Backbone extensions for Groupon Now!: changing the router
4079 to handle URLs with querystring parameters, and adding a simple
4080 in-memory store for caching repeated requests for the same data.
4081 </p>
4082
4083 <div style="text-align: center;">
4084 <a href="http://www.groupon.com/now">
4085 <img width="550" height="466" data-original="docs/images/groupon.jpg" alt="Groupon Now!" class="example_retina" />
4086 </a>
4087 </div>
4088
4089 <h2 id="examples-basecamp">Basecamp</h2>
4090
4091 <p>
4092 <a href="http://37signals.com/">37Signals</a> chose Backbone.js to create
4093 the <a href="http://basecamp.com/calendar">calendar feature</a> of its
4094 popular project management software <a href="http://basecamp.com/">Basecamp</a>.
4095 The Basecamp Calendar uses Backbone.js models and views in conjunction with the
4096 <a href="https://github.com/sstephenson/eco">Eco</a> templating system to
4097 present a polished, highly interactive group scheduling interface.
4098 </p>
4099
4100 <div style="text-align: center;">
4101 <a href="http://basecamp.com/calendar">
4102 <img width="530" height="380" data-original="docs/images/basecamp-calendar.jpg" alt="Basecamp Calendar" class="example_retina" />
4103 </a>
4104 </div>
4105
4106 <h2 id="examples-slavery-footprint">Slavery Footprint</h2>
4107
4108 <p>
4109 <a href="http://slaveryfootprint.org/survey">Slavery Footprint</a>
4110 allows consumers to visualize how their consumption habits are
4111 connected to modern-day slavery and provides them with an opportunity
4112 to have a deeper conversation with the companies that manufacture the
4113 goods they purchased.
4114 Based in Oakland, California, the Slavery Footprint team works to engage
4115 individuals, groups, and businesses to build awareness for and create
4116 deployable action against forced labor, human trafficking, and modern-day
4117 slavery through online tools, as well as off-line community education and
4118 mobilization programs.
4119 </p>
4120
4121 <div style="text-align: center;">
4122 <a href="http://slaveryfootprint.org/survey">
4123 <img width="550" height="394" data-original="docs/images/slavery-footprint.jpg" alt="Slavery Footprint" class="example_retina" />
4124 </a>
4125 </div>
4126
4127 <h2 id="examples-stripe">Stripe</h2>
4128
4129 <p>
4130 <a href="https://stripe.com">Stripe</a> provides an API for accepting
4131 credit cards on the web. Stripe's
4132 <a href="https://manage.stripe.com">management interface</a> was recently
4133 rewritten from scratch in CoffeeScript using Backbone.js as the primary
4134 framework, <a href="https://github.com/sstephenson/eco">Eco</a> for templates, <a href="http://sass-lang.com/">Sass</a> for stylesheets, and <a href="https://github.com/sstephenson/stitch">Stitch</a> to package
4135 everything together as <a href="http://commonjs.org/">CommonJS</a> modules. The new app uses
4136 <a href="https://stripe.com/docs/api">Stripe's API</a> directly for the
4137 majority of its actions; Backbone.js models made it simple to map
4138 client-side models to their corresponding RESTful resources.
4139 </p>
4140
4141 <div style="text-align: center;">
4142 <a href="https://stripe.com">
4143 <img width="555" height="372" data-original="docs/images/stripe.png" alt="Stripe" class="example_retina" />
4144 </a>
4145 </div>
4146
4147 <h2 id="examples-airbnb">Airbnb</h2>
4148
4149 <p>
4150 <a href="http://airbnb.com">Airbnb</a> uses Backbone in many of its products.
4151 It started with <a href="http://m.airbnb.com">Airbnb Mobile Web</a>
4152 (built in six weeks by a team of three) and has since grown to
4153 <a href="https://www.airbnb.com/wishlists/popular">Wish Lists</a>,
4154 <a href="http://www.airbnb.com/match">Match</a>,
4155 <a href="http://www.airbnb.com/s/">Search</a>, Communities, Payments, and
4156 Internal Tools.
4157 </p>
4158
4159 <div style="text-align: center;">
4160 <a href="http://m.airbnb.com/">
4161 <img width="500" height="489" data-original="docs/images/airbnb.png" alt="Airbnb" class="example_image" />
4162 </a>
4163 </div>
4164
4165 <h2 id="examples-soundcloud">SoundCloud Mobile</h2>
4166
4167 <p>
4168 <a href="http://soundcloud.com">SoundCloud</a> is the leading sound sharing
4169 platform on the internet, and Backbone.js provides the foundation for
4170 <a href="http://m.soundcloud.com">SoundCloud Mobile</a>. The project uses
4171 the public SoundCloud <a href="http://soundcloud.com/developers">API</a>
4172 as a data source (channeled through a nginx proxy),
4173 <a href="https://github.com/BorisMoore/jquery-tmpl">jQuery templates</a>
4174 for the rendering, <a href="http://docs.jquery.com/Qunit">Qunit
4175 </a> and <a href="http://www.phantomjs.org/">PhantomJS</a> for
4176 the testing suite. The JS code, templates and CSS are built for the
4177 production deployment with various Node.js tools like
4178 <a href="https://github.com/dsimard/ready.js">ready.js</a>,
4179 <a href="https://github.com/mde/jake">Jake</a>,
4180 <a href="https://github.com/tmpvar/jsdom">jsdom</a>.
4181 The <b>Backbone.History</b> was modified to support the HTML5 <tt>history.pushState</tt>.
4182 <b>Backbone.sync</b> was extended with an additional SessionStorage based cache
4183 layer.
4184 </p>
4185
4186 <div style="text-align: center;">
4187 <a href="http://m.soundcloud.com">
4188 <img width="266" height="555" data-original="docs/images/soundcloud.png" alt="SoundCloud" class="example_image" />
4189 </a>
4190 </div>
4191
4192 <h2 id="examples-artsy">Art.sy</h2>
4193
4194 <p>
4195 <a href="http://artsy.net">Art.sy</a> is a place to discover art you'll
4196 love. Art.sy is built on Rails, using
4197 <a href="https://github.com/intridea/grape">Grape</a> to serve a robust
4198 <a href="http://artsy.net/api">JSON API</a>. The main site is a single page
4199 app written in CoffeeScript and uses Backbone to provide structure around
4200 this API. An admin panel and partner CMS have also been extracted into
4201 their own API-consuming Backbone projects.
4202 </p>
4203
4204 <div style="text-align: center;">
4205 <a href="http://artsy.net">
4206 <img width="550" height="550" data-original="docs/images/artsy.jpg" alt="Art.sy" class="example_retina" />
4207 </a>
4208 </div>
4209
4210 <h2 id="examples-pandora">Pandora</h2>
4211
4212 <p>
4213 When <a href="http://www.pandora.com/newpandora">Pandora</a> redesigned
4214 their site in HTML5, they chose Backbone.js to help
4215 manage the user interface and interactions. For example, there's a model
4216 that represents the "currently playing track", and multiple views that
4217 automatically update when the current track changes. The station list is a
4218 collection, so that when stations are added or changed, the UI stays up to date.
4219 </p>
4220
4221 <div style="text-align: center;">
4222 <a href="http://www.pandora.com/newpandora">
4223 <img width="476" height="359" data-original="docs/images/pandora.jpg" alt="Pandora" class="example_retina" />
4224 </a>
4225 </div>
4226
4227 <h2 id="examples-inkling">Inkling</h2>
4228
4229 <p>
4230 <a href="http://inkling.com/">Inkling</a> is a cross-platform way to
4231 publish interactive learning content.
4232 <a href="https://www.inkling.com/read/">Inkling for Web</a> uses Backbone.js
4233 to make hundreds of complex books — from student textbooks to travel guides and
4234 programming manuals — engaging and accessible on the web. Inkling supports
4235 WebGL-enabled 3D graphics, interactive assessments, social sharing,
4236 and a system for running practice code right
4237 in the book, all within a single page Backbone-driven app. Early on, the
4238 team decided to keep the site lightweight by using only Backbone.js and
4239 raw JavaScript. The result? Complete source code weighing in at a mere
4240 350kb with feature-parity across the iPad, iPhone and web clients.
4241 Give it a try with
4242 <a href="https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-4/function-definition-expressions">this excerpt from JavaScript: The Definitive Guide</a>.
4243 </p>
4244
4245 <div style="text-align: center;">
4246 <a href="http://inkling.com">
4247 <img width="550" height="361" data-original="docs/images/inkling.jpg" alt="Inkling" class="example_retina" />
4248 </a>
4249 </div>
4250
4251 <h2 id="examples-code-school">Code School</h2>
4252
4253 <p>
4254 <a href="http://www.codeschool.com">Code School</a> courses teach people
4255 about various programming topics like <a href="http://coffeescript.org">CoffeeScript</a>, CSS, Ruby on Rails,
4256 and more. The new Code School course
4257 <a href="http://coffeescript.codeschool.com/levels/1/challenges/1">challenge page</a>
4258 is built from the ground up on Backbone.js, using
4259 everything it has to offer: the router, collections, models, and complex
4260 event handling. Before, the page was a mess of <a href="http://jquery.com/">jQuery</a> DOM manipulation
4261 and manual Ajax calls. Backbone.js helped introduce a new way to
4262 think about developing an organized front-end application in JavaScript.
4263 </p>
4264
4265 <div style="text-align: center;">
4266 <a href="http://www.codeschool.com">
4267 <img width="550" height="482" data-original="docs/images/code-school.jpg" alt="Code School" class="example_retina" />
4268 </a>
4269 </div>
4270
4271 <h2 id="examples-cloudapp">CloudApp</h2>
4272
4273 <p>
4274 <a href="http://getcloudapp.com">CloudApp</a> is simple file and link
4275 sharing for the Mac. Backbone.js powers the web tools
4276 which consume the <a href="http://developer.getcloudapp.com">documented API</a>
4277 to manage Drops. Data is either pulled manually or pushed by
4278 <a href="http://pusher.com">Pusher</a> and fed to
4279 <a href="http://github.com/janl/mustache.js">Mustache</a> templates for
4280 rendering. Check out the <a href="http://cloudapp.github.com/engine">annotated source code</a>
4281 to see the magic.
4282 </p>
4283
4284 <div style="text-align: center;">
4285 <a href="http://getcloudapp.com">
4286 <img width="550" height="426" data-original="docs/images/cloudapp.jpg" alt="CloudApp" class="example_retina" />
4287 </a>
4288 </div>
4289
4290 <h2 id="examples-seatgeek">SeatGeek</h2>
4291
4292 <p>
4293 <a href="http://seatgeek.com">SeatGeek</a>'s stadium ticket maps were originally
4294 developed with <a href="http://prototypejs.org/">Prototype.js</a>. Moving to Backbone.js and <a href="http://jquery.com/">jQuery</a> helped organize
4295 a lot of the UI code, and the increased structure has made adding features
4296 a lot easier. SeatGeek is also in the process of building a mobile
4297 interface that will be Backbone.js from top to bottom.
4298 </p>
4299
4300 <div style="text-align: center;">
4301 <a href="http://seatgeek.com">
4302 <img width="550" height="455" data-original="docs/images/seatgeek.jpg" alt="SeatGeek" class="example_retina" />
4303 </a>
4304 </div>
4305
4306 <h2 id="examples-easel">Easel</h2>
4307
4308 <p>
4309 <a href="http://easel.io">Easel</a> is an in-browser, high fidelity web
4310 design tool that integrates with your design and development
4311 process. The Easel team uses CoffeeScript, Underscore.js and Backbone.js for
4312 their <a href="http://easel.io/demo">rich visual editor</a> as well as other
4313 management functions throughout the site. The structure of Backbone allowed
4314 the team to break the complex problem of building a visual editor into
4315 manageable components and still move quickly.
4316 </p>
4317
4318 <div style="text-align: center;">
4319 <a href="http://easel.io">
4320 <img width="550" height="395" data-original="docs/images/easel.jpg" alt="Easel" class="example_retina" />
4321 </a>
4322 </div>
4323
4324 <h2 id="examples-jolicloud">Jolicloud</h2>
4325
4326 <p>
4327 <a href="http://www.jolicloud.com/">Jolicloud</a> is an open and independent
4328 platform and <a href="http://www.jolicloud.com/jolios">operating system</a>
4329 that provides music playback, video streaming, photo browsing and
4330 document editing &mdash; transforming low cost computers into beautiful cloud devices.
4331 The <a href="https://my.jolicloud.com/">new Jolicloud HTML5 app</a> was built
4332 from the ground up using Backbone and talks to the
4333 <a href="http://developers.jolicloud.com">Jolicloud Platform</a>, which is
4334 based on Node.js. Jolicloud works offline using the HTML5 AppCache, extends
4335 Backbone.sync to store data in IndexedDB or localStorage, and communicates
4336 with the <a href="http://www.jolicloud.com/jolios">Joli OS</a> via WebSockets.
4337 </p>
4338
4339 <div style="text-align: center;">
4340 <a href="http://jolicloud.com/">
4341 <img width="510" height="384" data-original="docs/images/jolicloud.jpg" alt="Jolicloud" class="example_retina" />
4342 </a>
4343 </div>
4344
4345 <h2 id="examples-salon">Salon.io</h2>
4346
4347 <p>
4348 <a href="http://salon.io">Salon.io</a> provides a space where photographers,
4349 artists and designers freely arrange their visual art on virtual walls.
4350 <a href="http://salon.io">Salon.io</a> runs on <a href="http://rubyonrails.org/">Rails</a>, but does not use
4351 much of the traditional stack, as the entire frontend is designed as a
4352 single page web app, using Backbone.js, <a href="http://brunch.io/">Brunch</a> and
4353 <a href="http://coffeescript.org">CoffeeScript</a>.
4354 </p>
4355
4356 <div style="text-align: center;">
4357 <a href="http://salon.io">
4358 <img width="550" height="483" data-original="docs/images/salon.jpg" alt="Salon.io" class="example_retina" />
4359 </a>
4360 </div>
4361
4362 <h2 id="examples-tilemill">TileMill</h2>
4363
4364 <p>
4365 Our fellow
4366 <a href="http://www.newschallenge.org/">Knight Foundation News Challenge</a>
4367 winners, <a href="http://mapbox.com/">MapBox</a>, created an open-source
4368 map design studio with Backbone.js:
4369 <a href="https://www.mapbox.com/tilemill/">TileMill</a>.
4370 TileMill lets you manage map layers based on shapefiles and rasters, and
4371 edit their appearance directly in the browser with the
4372 <a href="https://github.com/mapbox/carto">Carto styling language</a>.
4373 Note that the gorgeous <a href="http://mapbox.com/">MapBox</a> homepage
4374 is also a Backbone.js app.
4375 </p>
4376
4377 <div style="text-align: center;">
4378 <a href="https://www.mapbox.com/tilemill/">
4379 <img width="544" height="375" data-original="docs/images/tilemill.jpg" alt="TileMill" class="example_retina" />
4380 </a>
4381 </div>
4382
4383 <h2 id="examples-blossom">Blossom</h2>
4384
4385 <p>
4386 <a href="http://blossom.io">Blossom</a> is a lightweight project management
4387 tool for lean teams. Backbone.js is heavily used in combination with
4388 <a href="http://coffeescript.org">CoffeeScript</a> to provide a smooth
4389 interaction experience. The app is packaged with <a href="http://brunch.io">Brunch</a>.
4390 The RESTful backend is built with <a href="http://flask.pocoo.org/">Flask</a> on Google App Engine.
4391 </p>
4392
4393 <div style="text-align: center;">
4394 <a href="http://blossom.io">
4395 <img width="550" height="367" data-original="docs/images/blossom.jpg" alt="Blossom" class="example_retina" />
4396 </a>
4397 </div>
4398
4399 <h2 id="examples-trello">Trello</h2>
4400
4401 <p>
4402 <a href="http://trello.com">Trello</a> is a collaboration tool that
4403 organizes your projects into boards. A Trello board holds many lists of
4404 cards, which can contain checklists, files and conversations, and may be
4405 voted on and organized with labels. Updates on the board happen in
4406 real time. The site was built ground up using Backbone.js for all the
4407 models, views, and routes.
4408 </p>
4409
4410 <div style="text-align: center;">
4411 <a href="http://trello.com">
4412 <img width="550" height="416" data-original="docs/images/trello.jpg" alt="Trello" class="example_retina" />
4413 </a>
4414 </div>
4415
4416 <h2 id="examples-tzigla">Tzigla</h2>
4417
4418 <p>
4419 <a href="http://twitter.com/evilchelu">Cristi Balan</a> and
4420 <a href="http://dira.ro">Irina Dumitrascu</a> created
4421 <a href="http://tzigla.com">Tzigla</a>, a collaborative drawing
4422 application where artists make tiles that connect to each other to
4423 create <a href="http://tzigla.com/boards/1">surreal drawings</a>.
4424 Backbone models help organize the code, routers provide
4425 <a href="http://tzigla.com/boards/1#!/tiles/2-2">bookmarkable deep links</a>,
4426 and the views are rendered with
4427 <a href="https://github.com/creationix/haml-js">haml.js</a> and
4428 <a href="http://zeptojs.com/">Zepto</a>.
4429 Tzigla is written in Ruby (<a href="http://rubyonrails.org/">Rails</a>) on the backend, and
4430 <a href="http://coffeescript.org">CoffeeScript</a> on the frontend, with
4431 <a href="http://documentcloud.github.com/jammit/">Jammit</a>
4432 prepackaging the static assets.
4433 </p>
4434
4435 <div style="text-align: center;">
4436 <a href="http://www.tzigla.com/">
4437 <img width="550" height="376" data-original="docs/images/tzigla.jpg" alt="Tzigla" class="example_retina" />
4438 </a>
4439 </div>
4440
4441 <h2 id="changelog">Change Log</h2>
4442
4443 <b class="header" id="1.4.1">1.4.1</b> &mdash; <small><i>Feb. 26, 2022</i></small>
4444 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.4.0...1.4.1">Diff</a>
4445 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.4.1/index.html">Docs</a>
4446 <br />
4447 <ul style="margin-top: 5px;">
4448 <li>
4449 Improved support for polymorphic collections in which two or more model
4450 types might have different <tt>idAttribute</tt>s.
4451 <tt>Collection.modelId()</tt> overrides can now exploit the fact that
4452 internal methods pass the <tt>idAttribute</tt> as a second argument to
4453 <tt>modelId</tt>.
4454 </li>
4455 <li>
4456 Fixed a temporary inconsistency in a collection's internal
4457 administration during model <tt>change</tt> events. Models (and by
4458 extension, collections) now emit a specialized <tt>changeId</tt> event
4459 when the id changes.
4460 </li>
4461 <li>
4462 Fixed an issue where an ES6 class or object method could not be used as
4463 the <tt>model</tt> for a collection due to the lack of a
4464 <tt>prototype</tt>.
4465 </li>
4466 <li>
4467 Restored continuous integration using GitHub Actions and cross-browser
4468 testing using Sauce Labs.
4469 </li>
4470 <li>
4471 Several improvements to the online documentation.
4472 </li>
4473 <li>
4474 Due to upgraded development tools, the annotated sources of the example
4475 code as well as the sourcemap of the minified bundle have changed
4476 filenames. Aliases and redirects in the old locations are kept for
4477 backwards compatibility.
4478 </li>
4479 </ul>
4480
4481 <b class="header" id="1.4.0">1.4.0</b> &mdash; <small><i>Feb. 19, 2019</i></small>
4482 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.3.3...1.4.0">Diff</a>
4483 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.4.0/index.html">Docs</a>
4484 <br />
4485 <ul style="margin-top: 5px;">
4486 <li>
4487 Collections now support the <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols">Javascript Iterator Protocol!</a>
4488 </li>
4489 <li>
4490 <tt>listenTo</tt> uses the listened object's public <tt>on</tt> method.
4491 This helps maintain interoperability between Backbone and other event
4492 libraries (including Node.js).
4493 </li>
4494 <li>
4495 Added support for setting instance properties before the constructor in
4496 <tt>ES2015 classes</tt> with a <tt>preinitialize</tt> method.
4497 </li>
4498 <li>
4499 <tt>Collection.get</tt> now checks if obj is a <tt>Model</tt> to allow
4500 retrieving models with an `attributes` key.
4501 </li>
4502 <li>
4503 Fixed several issues with Router's URL hashing and parsing.
4504 </li>
4505 </ul>
4506
4507 <b class="header" id="1.3.3">1.3.3</b> &mdash; <small><i>Apr. 5, 2016</i></small>
4508 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.2.3...1.3.3">Diff</a>
4509 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.3.3/index.html">Docs</a>
4510 <br />
4511 <ul style="margin-top: 5px;">
4512 <li>
4513 Added <tt>findIndex</tt> and <tt>findLastIndex</tt> Underscore methods to
4514 <tt>Collection</tt>.
4515 </li>
4516 <li>
4517 Added <tt>options.changes</tt> to <tt>Collection</tt> "update" event which
4518 includes added, merged, and removed models.
4519 </li>
4520 <li>
4521 Added support for <tt>Collection#mixin</tt> and <tt>Model#mixin</tt>.
4522 </li>
4523 <li>
4524 Ensured <tt>Collection#reduce</tt> and <tt>Collection#reduceRight</tt>
4525 work without an initial <tt>accumulator</tt> value.
4526 </li>
4527 <li>
4528 Ensured <tt>Collection#_removeModels</tt> always returns an array.
4529 </li>
4530 <li>
4531 Fixed a bug where <tt>Events.once</tt> with object syntax failed to bind
4532 context.
4533 </li>
4534 <li>
4535 Fixed <tt>Collection#_onModelEvent</tt> regression where triggering a
4536 <tt>change</tt> event without a <tt>model</tt> would error.
4537 </li>
4538 <li>
4539 Fixed <tt>Collection#set</tt> regression when <tt>parse</tt> returns a
4540 falsy value.
4541 </li>
4542 <li>
4543 Fixed <tt>Model#id</tt> regression where <tt>id</tt> would be
4544 unintentionally <tt>undefined</tt>.
4545 </li>
4546 <li>
4547 Fixed <tt>_removeModels</tt> regression which could cause an infinite loop
4548 under certain conditions.
4549 </li>
4550 <li>
4551 Removed <tt>component</tt> package support.
4552 </li>
4553 <li>
4554 Note that 1.3.3 fixes several bugs in versions 1.3.0 to 1.3.2. Please upgrade
4555 immediately if you are on one of those versions.
4556 </li>
4557 </ul>
4558
4559 <b class="header" id="1.2.3">1.2.3</b> &mdash; <small><i>Sept. 3, 2015</i></small>
4560 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.2.2...1.2.3">Diff</a>
4561 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.2.3/index.html">Docs</a>
4562 <br />
4563 <ul style="margin-top: 5px;">
4564 <li>
4565 Fixed a minor regression in 1.2.2 that would cause an error when adding
4566 a model to a collection <tt>at</tt> an out of bounds index.
4567 </li>
4568 </ul>
4569
4570 <b class="header" id="1.2.2">1.2.2</b> &mdash; <small><i>Aug. 19, 2015</i></small>
4571 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.2.1...1.2.2">Diff</a>
4572 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.2.2/index.html">Docs</a>
4573 <br />
4574 <ul style="margin-top: 5px;">
4575 <li>
4576 Collection methods <tt>find</tt>, <tt>filter</tt>, <tt>reject</tt>, <tt>every</tt>,
4577 <tt>some</tt>, and <tt>partition</tt> can now take a model-attributes-style predicate:
4578 <tt>this.collection.reject({user: 'guybrush'})</tt>.
4579 </li>
4580 <li>
4581 Backbone Events once again supports multiple-event maps
4582 (<tt>obj.on({'error change': action})</tt>). This was a previously
4583 undocumented feature inadvertently removed in 1.2.0.
4584 </li>
4585 <li>
4586 Added <tt>Collection#includes</tt> as an alias of <tt>Collection#contains</tt>
4587 and as a replacement for <tt>Collection#include</tt> in Underscore.js >= 1.8.
4588 </li>
4589 </ul>
4590
4591 <b class="header" id="1.2.1">1.2.1</b> &mdash; <small><i>Jun. 4, 2015</i></small>
4592 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.2.0...1.2.1">Diff</a>
4593 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.2.1/index.html">Docs</a>
4594 <br />
4595 <ul style="margin-top: 5px;">
4596 <li>
4597 <tt>Collection#add</tt> now avoids trying to parse a model instance when passed <tt>parse: false</tt>.
4598 </li>
4599 <li>
4600 Bug fix in <tt>Collection#remove</tt>. The removed models are now actually returned.
4601 </li>
4602 <li>
4603 <tt>Model#fetch</tt> no longer parses the response when passing <tt>parse: false</tt>.
4604 </li>
4605 <li>
4606 Bug fix for iframe-based History when used with JSDOM.
4607 </li>
4608 <li>
4609 Bug fix where <tt>Collection#invoke</tt> was not taking additional arguments.
4610 </li>
4611 <li>
4612 When using <tt>on</tt> with an event map, you can now pass the context as the
4613 second argument. This was a previously undocumented feature inadvertently
4614 removed in 1.2.0.
4615 </li>
4616 </ul>
4617
4618 <b class="header" id="1.2.0">1.2.0</b> &mdash; <small><i>May 13, 2015</i></small>
4619 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.1.2...1.2.0">Diff</a>
4620 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.2.0/index.html">Docs</a>
4621 <br />
4622 <ul style="margin-top: 5px;">
4623 <li>
4624 Added new hooks to Views to allow them to work without jQuery. See the
4625 <a href="https://github.com/jashkenas/backbone/wiki/Using-Backbone-without-jQuery">wiki page</a>
4626 for more info.
4627 </li>
4628 <li>
4629 As a neat side effect, Backbone.History no longer uses jQuery's
4630 event methods for <tt>pushState</tt> and <tt>hashChange</tt> listeners.
4631 We're native all the way.
4632 </li>
4633 <li>
4634 Also on the subject of jQuery, if you're using Backbone with CommonJS (node, browserify, webpack)
4635 Backbone will automatically try to load jQuery for you.
4636 </li>
4637 <li>
4638 Views now always delegate their events in <a href="#View-setElement">setElement</a>.
4639 You can no longer modify the events hash or your view's <tt>el</tt> property in
4640 <tt>initialize</tt>.
4641 </li>
4642 <li>
4643 Added an <tt>"update"</tt> event that triggers after any amount of
4644 models are added or removed from a collection. Handy to re-render lists
4645 of things without debouncing.
4646 </li>
4647 <li>
4648 <tt>Collection#at</tt> can take a negative index.
4649 </li>
4650 <li>
4651 Added <tt>modelId</tt> to Collection for generating unique ids on
4652 polymorphic collections. Handy for cases when your model ids would
4653 otherwise collide.
4654 </li>
4655 <li>
4656 Added an overridable <tt>_isModel</tt> for more advanced
4657 control of what's considered a model by your Collection.
4658 </li>
4659 <li>
4660 The <tt>success</tt> callback passed to <tt>Model#destroy</tt> is always
4661 called asynchronously now.
4662 </li>
4663 <li>
4664 <tt>Router#execute</tt> passes back the route name as its third argument.
4665 </li>
4666 <li>
4667 Cancel the current Router transition by returning <tt>false</tt> in
4668 <tt>Router#execute</tt>. Great for checking logged-in status or other
4669 prerequisites.
4670 </li>
4671 <li>
4672 Added <tt>getSearch</tt> and <tt>getPath</tt> methods to Backbone.History as
4673 cross-browser and overridable ways of slicing up the URL.
4674 </li>
4675 <li>
4676 Added <tt>delegate</tt> and <tt>undelegate</tt> as finer-grained versions
4677 of <tt>delegateEvents</tt> and <tt>undelegateEvents</tt>. Useful for plugin
4678 authors to use a consistent events interface in Backbone.
4679 </li>
4680 <li>
4681 A collection will only fire a "sort" event if its order was actually
4682 updated, not on every <tt>set</tt>.
4683 </li>
4684 <li>
4685 Any passed <tt>options.attrs</tt> are now respected when saving a model with
4686 <tt>patch: true</tt>.
4687 </li>
4688 <li>
4689 <tt>Collection#clone</tt> now sets the <tt>model</tt> and <tt>comparator</tt>
4690 functions of the cloned collection to the new one.
4691 </li>
4692 <li>
4693 Adding models to your Collection when specifying an <tt>at</tt> position
4694 now sends the actual position of your model in the <tt>add</tt>
4695 event, not just the one you've passed in.
4696 </li>
4697 <li>
4698 <tt>Collection#remove</tt> will now only return a list of models that
4699 have actually been removed from the collection.
4700 </li>
4701 <li>
4702 Fixed loading Backbone.js in strict ES2015 module loaders.
4703 </li>
4704 </ul>
4705
4706 <b class="header" id="1.1.2">1.1.2</b> &mdash; <small><i>Feb. 20, 2014</i></small>
4707 &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.1.1...1.1.2">Diff</a>
4708 &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.1.2/index.html">Docs</a>
4709 <br />
4710 <ul style="margin-top: 5px;">
4711 <li>
4712 Backbone no longer tries to require jQuery in Node/CommonJS environments,
4713 for better compatibility with folks using Browserify.
4714 If you'd like to have Backbone use jQuery from Node, assign it like so:
4715 <tt>Backbone.$ = require('jquery');</tt>
4716 </li>
4717 <li>
4718 Bugfix for route parameters with newlines in them.
4719 </li>
4720 </ul>
4721
4722 <b class="header" id="1.1.1">1.1.1</b> &mdash; <small><i>Feb. 13, 2014</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.1.0...1.1.1">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.1.1/index.html">Docs</a><br />
4723 <ul style="margin-top: 5px;">
4724 <li>
4725 Backbone now registers itself for AMD (Require.js), Bower and Component,
4726 as well as being a CommonJS module and a regular (Java)Script. Whew.
4727 </li>
4728 <li>
4729 Added an <tt>execute</tt> hook to the Router, which allows you to hook
4730 in and custom-parse route arguments, like query strings, for example.
4731 </li>
4732 <li>
4733 Performance fine-tuning for Backbone Events.
4734 </li>
4735 <li>
4736 Better matching for Unicode in routes, in old browsers.
4737 </li>
4738 <li>
4739 Backbone Routers now handle query params in route fragments, passing
4740 them into the handler as the last argument. Routes specified as
4741 strings should no longer include the query string
4742 (<tt>'foo?:query'</tt> should be <tt>'foo'</tt>).
4743 </li>
4744 </ul>
4745
4746 <b class="header" id="1.1.0">1.1.0</b> &mdash; <small><i>Oct. 10, 2013</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/1.0.0...1.1.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.1.0/index.html">Docs</a><br />
4747 <ul style="margin-top: 5px;">
4748 <li>
4749 Made the return values of Collection's <tt>set</tt>, <tt>add</tt>,
4750 <tt>remove</tt>, and <tt>reset</tt> more useful. Instead of returning
4751 <tt>this</tt>, they now return the changed (added, removed or updated)
4752 model or list of models.
4753 </li>
4754 <li>
4755 Backbone Views no longer automatically attach options passed to the constructor as
4756 <tt>this.options</tt> and Backbone Models no longer attach <tt>url</tt> and
4757 <tt>urlRoot</tt> options, but you can do it yourself if you prefer.
4758 </li>
4759 <li>
4760 All <tt>"invalid"</tt> events now pass consistent arguments. First the
4761 model in question, then the error object, then options.
4762 </li>
4763 <li>
4764 You are no longer permitted to change the <b>id</b> of your model during
4765 <tt>parse</tt>. Use <tt>idAttribute</tt> instead.
4766 </li>
4767 <li>
4768 On the other hand, <tt>parse</tt> is now an excellent place to extract
4769 and vivify incoming nested JSON into associated submodels.
4770 </li>
4771 <li>
4772 Many tweaks, optimizations and bugfixes relating to Backbone 1.0,
4773 including URL overrides, mutation of options, bulk ordering, trailing
4774 slashes, edge-case listener leaks, nested model parsing...
4775 </li>
4776 </ul>
4777
4778 <b class="header" id="1.0.0">1.0.0</b> &mdash; <small><i>March 20, 2013</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.9.10...1.0.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/1.0.0/index.html">Docs</a><br />
4779 <ul style="margin-top: 5px;">
4780 <li>
4781 Renamed Collection's "update" to <a href="#Collection-set">set</a>, for
4782 parallelism with the similar <tt>model.set()</tt>, and contrast with
4783 <a href="#Collection-reset">reset</a>. It's now the default
4784 updating mechanism after a <a href="#Collection-fetch">fetch</a>. If you'd
4785 like to continue using "reset", pass <tt>{reset: true}</tt>.
4786 </li>
4787 <li>
4788 Your route handlers will now receive their URL parameters pre-decoded.
4789 </li>
4790 <li>
4791 Added <a href="#Events-listenToOnce">listenToOnce</a> as the analogue of
4792 <a href="#Events-once">once</a>.
4793 </li>
4794 <li>
4795 Added the <a href="#Collection-findWhere">findWhere</a> method to Collections,
4796 similar to <a href="#Collection-where">where</a>.
4797 </li>
4798 <li>
4799 Added the <tt>keys</tt>, <tt>values</tt>, <tt>pairs</tt>, <tt>invert</tt>,
4800 <tt>pick</tt>, and <tt>omit</tt> Underscore.js methods to Backbone Models.
4801 </li>
4802 <li>
4803 The routes in a Router's route map may now be function literals,
4804 instead of references to methods, if you like.
4805 </li>
4806 <li>
4807 <tt>url</tt> and <tt>urlRoot</tt> properties may now be passed as options
4808 when instantiating a new Model.
4809 </li>
4810 </ul>
4811
4812 <b class="header" id="0.9.10">0.9.10</b> &mdash; <small><i>Jan. 15, 2013</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.9.9...0.9.10">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.9.10/index.html">Docs</a><br />
4813 <ul style="margin-top: 5px;">
4814 <li>
4815 A <tt>"route"</tt> event is triggered on the router in addition
4816 to being fired on <tt>Backbone.history</tt>.
4817 </li>
4818 <li>
4819 Model validation is now only enforced by default in
4820 <tt>Model#save</tt> and no longer enforced by default upon
4821 construction or in <tt>Model#set</tt>, unless the <tt>{validate:true}</tt>
4822 option is passed.
4823 </li>
4824 <li>
4825 <tt>View#make</tt> has been removed. You'll need to use <tt>$</tt> directly to
4826 construct DOM elements now.
4827 </li>
4828 <li>
4829 Passing <tt>{silent:true}</tt> on change will no longer delay individual
4830 <tt>"change:attr"</tt> events, instead they are silenced entirely.
4831 </li>
4832 <li>
4833 The <tt>Model#change</tt> method has been removed, as delayed attribute
4834 changes are no longer available.
4835 </li>
4836 <li>
4837 Bug fix on <tt>change</tt> where attribute comparison uses <tt>!==</tt>
4838 instead of <tt>_.isEqual</tt>.
4839 </li>
4840 <li>
4841 Bug fix where an empty response from the server on save would not call
4842 the success function.
4843 </li>
4844 <li>
4845 <tt>parse</tt> now receives <tt>options</tt> as its second argument.
4846 </li>
4847 <li>
4848 Model validation now fires <tt>invalid</tt> event instead of
4849 <tt>error</tt>.
4850 </li>
4851 </ul>
4852
4853 <b class="header" id="0.9.9">0.9.9</b> &mdash; <small><i>Dec. 13, 2012</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.9.2...0.9.9">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.9.9/index.html">Docs</a><br />
4854 <ul style="margin-top: 5px;">
4855 <li>
4856 Added <a href="#Events-listenTo">listenTo</a>
4857 and <a href="#Events-stopListening">stopListening</a> to Events. They
4858 can be used as inversion-of-control flavors of <tt>on</tt> and <tt>off</tt>,
4859 for convenient unbinding of all events an object is currently listening to.
4860 <tt>view.remove()</tt> automatically calls <tt>view.stopListening()</tt>.
4861 </li>
4862 <li>
4863 When using <tt>add</tt> on a collection, passing <tt>{merge: true}</tt>
4864 will now cause duplicate models to have their attributes merged in to
4865 the existing models, instead of being ignored.
4866 </li>
4867 <li>
4868 Added <a href="#Collection-update">update</a> (which is also available as
4869 an option to <tt>fetch</tt>) for "smart" updating of sets of models.
4870 </li>
4871 <li>
4872 HTTP <tt>PATCH</tt> support in <a href="#Model-save">save</a> by passing
4873 <tt>{patch: true}</tt>.
4874 </li>
4875 <li>
4876 The <tt>Backbone</tt> object now extends <tt>Events</tt> so that you can
4877 use it as a global event bus, if you like.
4878 </li>
4879 <li>
4880 Added a <tt>"request"</tt> event to <a href="#Sync">Backbone.sync</a>,
4881 which triggers whenever a request begins to be made to the server.
4882 The natural complement to the <tt>"sync"</tt> event.
4883 </li>
4884 <li>
4885 Router URLs now support optional parts via parentheses, without having
4886 to use a regex.
4887 </li>
4888 <li>
4889 Backbone events now supports <tt>once</tt>, similar to Node's <tt>once</tt>,
4890 or jQuery's <tt>one</tt>.
4891 </li>
4892 <li>
4893 Backbone events now support jQuery-style event maps <tt>obj.on({click: action})</tt>.
4894 </li>
4895 <li>
4896 While listening to a <tt>reset</tt> event, the list of previous models
4897 is now available in <tt>options.previousModels</tt>, for convenience.
4898 </li>
4899 <li>
4900 <a href="#Model-validate">Validation</a> now occurs even during "silent"
4901 changes. This change means that the <tt>isValid</tt> method has
4902 been removed. Failed validations also trigger an error, even if an error
4903 callback is specified in the options.
4904 </li>
4905 <li>
4906 Consolidated <tt>"sync"</tt> and <tt>"error"</tt> events within
4907 <a href="#Sync">Backbone.sync</a>. They are now triggered regardless
4908 of the existence of <tt>success</tt> or <tt>error</tt> callbacks.
4909 </li>
4910 <li>
4911 For mixed-mode APIs, <tt>Backbone.sync</tt> now accepts
4912 <tt>emulateHTTP</tt> and <tt>emulateJSON</tt> as inline options.
4913 </li>
4914 <li>
4915 Collections now also proxy Underscore method name aliases (collect,
4916 inject, foldl, foldr, head, tail, take, and so on...)
4917 </li>
4918 <li>
4919 Removed <tt>getByCid</tt> from Collections. <tt>collection.get</tt> now
4920 supports lookup by both <tt>id</tt> and <tt>cid</tt>.
4921 </li>
4922 <li>
4923 After fetching a model or a collection, <i>all</i> defined <tt>parse</tt>
4924 functions will now be run. So fetching a collection and getting back new
4925 models could cause both the collection to parse the list, and then each model
4926 to be parsed in turn, if you have both functions defined.
4927 </li>
4928 <li>
4929 Bugfix for normalizing leading and trailing slashes in the Router
4930 definitions. Their presence (or absence) should not affect behavior.
4931 </li>
4932 <li>
4933 When declaring a View, <tt>options</tt>, <tt>el</tt>, <tt>tagName</tt>,
4934 <tt>id</tt> and <tt>className</tt> may now be defined as functions, if
4935 you want their values to be determined at runtime.
4936 </li>
4937 <li>
4938 Added a <tt>Backbone.ajax</tt> hook for more convenient overriding of
4939 the default use of <tt>$.ajax</tt>. If AJAX is too passé, set it to your
4940 preferred method for server communication.
4941 </li>
4942 <li>
4943 <tt>Collection#sort</tt> now triggers a <tt>sort</tt> event, instead
4944 of a <tt>reset</tt> event.
4945 </li>
4946 <li>
4947 Calling <tt>destroy</tt> on a Model will now return <tt>false</tt> if
4948 the model <tt>isNew</tt>.
4949 </li>
4950 <li>
4951 To set what library Backbone uses for DOM manipulation and Ajax calls,
4952 use <tt>Backbone.$ = ...</tt> instead of <tt>setDomLibrary</tt>.
4953 </li>
4954 <li>
4955 Removed the <tt>Backbone.wrapError</tt> helper method. Overriding
4956 <tt>sync</tt> should work better for those particular use cases.
4957 </li>
4958 <li>
4959 To improve the performance of <tt>add</tt>, <tt>options.index</tt>
4960 will no longer be set in the <tt>add</tt> event callback.
4961 <tt>collection.indexOf(model)</tt> can be used to retrieve the index
4962 of a model as necessary.
4963 </li>
4964 <li>
4965 For semantic and cross browser reasons, routes will now ignore search
4966 parameters. Routes like <tt>search?query=…&amp;page=3</tt> should become
4967 <tt>search/…/3</tt>.
4968 </li>
4969 <li>
4970 <tt>Model#set</tt> no longer accepts another model as an argument. This leads
4971 to subtle problems and is easily replaced with <tt>model.set(other.attributes)</tt>.
4972 </li>
4973 </ul>
4974
4975 <b class="header" id="0.9.2">0.9.2</b> &mdash; <small><i>March 21, 2012</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.9.1...0.9.2">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.9.2/index.html">Docs</a><br />
4976 <ul style="margin-top: 5px;">
4977 <li>
4978 Instead of throwing an error when adding duplicate models to a collection,
4979 Backbone will now silently skip them instead.
4980 </li>
4981 <li>
4982 Added <a href="#Collection-push">push</a>,
4983 <a href="#Collection-pop">pop</a>,
4984 <a href="#Collection-unshift">unshift</a>, and
4985 <a href="#Collection-shift">shift</a> to collections.
4986 </li>
4987 <li>
4988 A model's <a href="#Model-changed">changed</a> hash is now exposed for
4989 easy reading of the changed attribute delta, since the model's last
4990 <tt>"change"</tt> event.
4991 </li>
4992 <li>
4993 Added <a href="#Collection-where">where</a> to collections for simple
4994 filtering.
4995 </li>
4996 <li>
4997 You can now use a single <a href="#Events-off">off</a> call
4998 to remove all callbacks bound to a specific object.
4999 </li>
5000 <li>
5001 Bug fixes for nested individual change events, some of which may be
5002 "silent".
5003 </li>
5004 <li>
5005 Bug fixes for URL encoding in <tt>location.hash</tt> fragments.
5006 </li>
5007 <li>
5008 Bug fix for client-side validation in advance of a <tt>save</tt> call
5009 with <tt>{wait: true}</tt>.
5010 </li>
5011 <li>
5012 Updated / refreshed the example
5013 <a href="examples/todos/index.html">Todo List</a> app.
5014 </li>
5015 </ul>
5016
5017 <b class="header" id="0.9.1">0.9.1</b> &mdash; <small><i>Feb. 2, 2012</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.9.0...0.9.1">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.9.1/index.html">Docs</a><br />
5018 <ul style="margin-top: 5px;">
5019 <li>
5020 Reverted to 0.5.3-esque behavior for validating models. Silent changes
5021 no longer trigger validation (making it easier to work with forms).
5022 Added an <tt>isValid</tt> function that you can use to check if a model
5023 is currently in a valid state.
5024 </li>
5025 <li>
5026 If you have multiple versions of jQuery on the page, you can now tell
5027 Backbone which one to use with <tt>Backbone.setDomLibrary</tt>.
5028 </li>
5029 <li>
5030 Fixes regressions in <b>0.9.0</b> for routing with "root", saving with
5031 both "wait" and "validate", and the order of nested "change" events.
5032 </li>
5033 </ul>
5034
5035 <b class="header" id="0.9.0">0.9.0</b> &mdash; <small><i>Jan. 30, 2012</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.5.3...0.9.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.9.0/index.html">Docs</a><br />
5036 <ul style="margin-top: 5px;">
5037 <li>
5038 Creating and destroying models with <tt>create</tt> and <tt>destroy</tt>
5039 are now optimistic by default. Pass <tt>{wait: true}</tt> as an option
5040 if you'd like them to wait for a successful server response to proceed.
5041 </li>
5042 <li>
5043 Two new properties on views: <tt>$el</tt> &mdash; a cached jQuery (or Zepto)
5044 reference to the view's element, and <tt>setElement</tt>, which should
5045 be used instead of manually setting a view's <tt>el</tt>. It will
5046 both set <tt>view.el</tt> and <tt>view.$el</tt> correctly, as well as
5047 re-delegating events on the new DOM element.
5048 </li>
5049 <li>
5050 You can now bind and trigger multiple spaced-delimited events at once.
5051 For example: <tt>model.on("change:name change:age", ...)</tt>
5052 </li>
5053 <li>
5054 When you don't know the key in advance, you may now call
5055 <tt>model.set(key, value)</tt> as well as <tt>save</tt>.
5056 </li>
5057 <li>
5058 Multiple models with the same <tt>id</tt> are no longer allowed in a
5059 single collection.
5060 </li>
5061 <li>
5062 Added a <tt>"sync"</tt> event, which triggers whenever a model's state
5063 has been successfully synced with the server (create, save, destroy).
5064 </li>
5065 <li>
5066 <tt>bind</tt> and <tt>unbind</tt> have been renamed to <tt>on</tt>
5067 and <tt>off</tt> for clarity, following jQuery's lead.
5068 The old names are also still supported.
5069 </li>
5070 <li>
5071 A Backbone collection's <tt>comparator</tt> function may now behave
5072 either like a <a href="http://underscorejs.org/#sortBy">sortBy</a>
5073 (pass a function that takes a single argument),
5074 or like a <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">sort</a>
5075 (pass a comparator function that expects two arguments). The comparator
5076 function is also now bound by default to the collection &mdash; so you
5077 can refer to <tt>this</tt> within it.
5078 </li>
5079 <li>
5080 A view's <tt>events</tt> hash may now also contain direct function
5081 values as well as the string names of existing view methods.
5082 </li>
5083 <li>
5084 Validation has gotten an overhaul &mdash; a model's <tt>validate</tt> function
5085 will now be run even for silent changes, and you can no longer create
5086 a model in an initially invalid state.
5087 </li>
5088 <li>
5089 Added <tt>shuffle</tt> and <tt>initial</tt> to collections, proxied
5090 from Underscore.
5091 </li>
5092 <li>
5093 <tt>Model#urlRoot</tt> may now be defined as a function as well as a
5094 value.
5095 </li>
5096 <li>
5097 <tt>View#attributes</tt> may now be defined as a function as well as a
5098 value.
5099 </li>
5100 <li>
5101 Calling <tt>fetch</tt> on a collection will now cause all fetched JSON
5102 to be run through the collection's model's <tt>parse</tt> function, if
5103 one is defined.
5104 </li>
5105 <li>
5106 You may now tell a router to <tt>navigate(fragment, {replace: true})</tt>,
5107 which will either use <tt>history.replaceState</tt> or
5108 <tt>location.hash.replace</tt>, in order to change the URL without adding
5109 a history entry.
5110 </li>
5111 <li>
5112 Within a collection's <tt>add</tt> and <tt>remove</tt> events, the index
5113 of the model being added or removed is now available as <tt>options.index</tt>.
5114 </li>
5115 <li>
5116 Added an <tt>undelegateEvents</tt> to views, allowing you to manually
5117 remove all configured event delegations.
5118 </li>
5119 <li>
5120 Although you shouldn't be writing your routes with them in any case &mdash;
5121 leading slashes (<tt>/</tt>) are now stripped from routes.
5122 </li>
5123 <li>
5124 Calling <tt>clone</tt> on a model now only passes the attributes
5125 for duplication, not a reference to the model itself.
5126 </li>
5127 <li>
5128 Calling <tt>clear</tt> on a model now removes the <tt>id</tt> attribute.
5129 </li>
5130 </ul>
5131
5132 <p>
5133 <b class="header" id="0.5.3">0.5.3</b> &mdash; <small><i>August 9, 2011</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.5.2...0.5.3">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.5.3/index.html">Docs</a><br />
5134 A View's <tt>events</tt> property may now be defined as a function, as well
5135 as an object literal, making it easier to programmatically define and inherit
5136 events. <tt>groupBy</tt> is now proxied from Underscore as a method on Collections.
5137 If the server has already rendered everything on page load, pass
5138 <tt>Backbone.history.start({silent: true})</tt> to prevent the initial route
5139 from triggering. Bugfix for pushState with encoded URLs.
5140 </p>
5141
5142 <p>
5143 <b class="header" id="0.5.2">0.5.2</b> &mdash; <small><i>July 26, 2011</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.5.1...0.5.2">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.5.2/index.html">Docs</a><br />
5144 The <tt>bind</tt> function, can now take an optional third argument, to specify
5145 the <tt>this</tt> of the callback function.
5146 Multiple models with the same <tt>id</tt> are now allowed in a collection.
5147 Fixed a bug where calling <tt>.fetch(jQueryOptions)</tt> could cause an
5148 incorrect URL to be serialized.
5149 Fixed a brief extra route fire before redirect, when degrading from
5150 <tt>pushState</tt>.
5151 </p>
5152
5153 <p>
5154 <b class="header" id="0.5.1">0.5.1</b> &mdash; <small><i>July 5, 2011</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.5.0...0.5.1">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.5.1/index.html">Docs</a><br />
5155 Cleanups from the 0.5.0 release, to wit: improved transparent upgrades from
5156 hash-based URLs to pushState, and vice-versa. Fixed inconsistency with
5157 non-modified attributes being passed to <tt>Model#initialize</tt>. Reverted
5158 a <b>0.5.0</b> change that would strip leading hashbangs from routes.
5159 Added <tt>contains</tt> as an alias for <tt>includes</tt>.
5160 </p>
5161
5162 <p>
5163 <b class="header" id="0.5.0">0.5.0</b> &mdash; <small><i>July 1, 2011</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.3.3...0.5.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.5.0/index.html">Docs</a><br />
5164 A large number of tiny tweaks and micro bugfixes, best viewed by looking
5165 at <a href="https://github.com/jashkenas/backbone/compare/0.3.3...0.5.0">the commit diff</a>.
5166 HTML5 <tt>pushState</tt> support, enabled by opting-in with:
5167 <tt>Backbone.history.start({pushState: true})</tt>.
5168 <tt>Controller</tt> was renamed to <tt>Router</tt>, for clarity.
5169 <tt>Collection#refresh</tt> was renamed to <tt>Collection#reset</tt> to emphasize
5170 its ability to both reset the collection with new models, as well as empty
5171 out the collection when used with no parameters.
5172 <tt>saveLocation</tt> was replaced with <tt>navigate</tt>.
5173 RESTful persistence methods (save, fetch, etc.) now return the jQuery deferred
5174 object for further success/error chaining and general convenience.
5175 Improved XSS escaping for <tt>Model#escape</tt>.
5176 Added a <tt>urlRoot</tt> option to allow specifying RESTful urls without
5177 the use of a collection.
5178 An error is thrown if <tt>Backbone.history.start</tt> is called multiple times.
5179 <tt>Collection#create</tt> now validates before initializing the new model.
5180 <tt>view.el</tt> can now be a jQuery string lookup.
5181 Backbone Views can now also take an <tt>attributes</tt> parameter.
5182 <tt>Model#defaults</tt> can now be a function as well as a literal attributes
5183 object.
5184 </p>
5185
5186 <p>
5187 <b class="header" id="0.3.3">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.3.2...0.3.3">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.3.3/index.html">Docs</a><br />
5188 Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
5189 jQuery, as a framework for DOM manipulation and Ajax support.
5190 Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
5191 attributes intended for HTML interpolation. When trying to persist a model,
5192 failed requests will now trigger an <tt>"error"</tt> event. The
5193 ubiquitous <tt>options</tt> argument is now passed as the final argument
5194 to all <tt>"change"</tt> events.
5195 </p>
5196
5197 <p>
5198 <b class="header" id="0.3.2">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.3.1...0.3.2">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.3.2/index.html">Docs</a><br />
5199 Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
5200 overridden on a per-model, or per-collection basis. Fixed recursion error
5201 when calling <tt>save</tt> with no changed attributes, within a
5202 <tt>"change"</tt> event.
5203 </p>
5204
5205 <p>
5206 <b class="header" id="0.3.1">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.3.0...0.3.1">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.3.1/index.html">Docs</a><br />
5207 All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
5208 model, so that views can listen for them without having to know about the
5209 collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
5210 <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
5211 Backbone routes are now able to load empty URL fragments.
5212 </p>
5213
5214 <p>
5215 <b class="header" id="0.3.0">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.2.0...0.3.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.3.0/index.html">Docs</a><br />
5216 Backbone now has <a href="#Controller">Controllers</a> and
5217 <a href="#History">History</a>, for doing client-side routing based on
5218 URL fragments.
5219 Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
5220 do <tt>PUT</tt> and <tt>DELETE</tt>.
5221 Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
5222 encoded requests.
5223 Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
5224 from a model.
5225 All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
5226 </p>
5227
5228 <p>
5229 <b class="header" id="0.2.0">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.1.2...0.2.0">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.2.0/index.html">Docs</a><br />
5230 Instead of requiring server responses to be namespaced under a <tt>model</tt>
5231 key, now you can define your own <a href="#Model-parse">parse</a> method
5232 to convert responses into attributes for Models and Collections.
5233 The old <tt>handleEvents</tt> function is now named
5234 <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
5235 called as part of the View's constructor.
5236 Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
5237 Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
5238 </p>
5239
5240 <p>
5241 <b class="header" id="0.1.2">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.1.1...0.1.2">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.1.2/index.html">Docs</a><br />
5242 Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
5243 attributes of single model from the server.
5244 An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
5245 as an option, which will be invoked if validation fails, overriding the
5246 <tt>"error"</tt> event.
5247 You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
5248 methods by setting <tt>Backbone.emulateHTTP = true</tt>.
5249 Existing Model and Collection data is no longer sent up unnecessarily with
5250 <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
5251 Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
5252 </p>
5253
5254 <p>
5255 <b class="header" id="0.1.1">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small> &mdash; <a href="https://github.com/jashkenas/backbone/compare/0.1.0...0.1.1">Diff</a> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.1.1/index.html">Docs</a><br />
5256 Added a convention for <tt>initialize</tt> functions to be called
5257 upon instance construction, if defined. Documentation tweaks.
5258 </p>
5259
5260 <p>
5261 <b class="header" id="0.1.0">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small> &mdash; <a href="https://cdn.statically.io/gh/jashkenas/backbone/0.1.0/index.html">Docs</a><br />
5262 Initial Backbone release.
5263 </p>
5264
5265 <p>
5266 <br />
5267 <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
•5268 A DocumentCloud Project
5269 </a>
5270 </p>
5271
5272 </div>
5273
•5274 <script src="/usr/share/javascript/underscore/underscore.js"></script>
5275 <script src="/usr/share/javascript/jquery/jquery.js"></script>
5276 <script src="/usr/share/javascript/jquery-lazyload/jquery.lazyload.js"></script>
5277 <script src="/usr/share/javascript/json/json2.js"></script>
5278 <script src="/usr/share/javascript/backbone/backbone.js"></script>
5279 <script src="docs/search.js"></script>
5280
5281 <script>
5282 // Set up the "play" buttons for each runnable code example.
5283 $(function() {
5284 $('.runnable').each(function() {
5285 var code = this;
5286 var button = '<div class="run" title="Run"></div>';
5287 $(button).insertBefore(code).bind('click', function(){
5288 eval($(code).text());
5289 });
5290 });
5291 $('[data-original]').lazyload();
5292 });
5293 </script>
5294
5295 </body>
5296 </html>