PageRenderTime 237ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/backbone/index.html

https://bitbucket.org/moonboots/backbone-everywhere
HTML | 2863 lines | 2452 code | 411 blank | 0 comment | 0 complexity | e2ef212d72b73e214a25274be3ba5dc3 MD5 | raw file
Possible License(s): MIT
  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. <title>Backbone.js</title>
  7. <style>
  8. body {
  9. font-size: 14px;
  10. line-height: 22px;
  11. font-family: Helvetica Neue, Helvetica, Arial;
  12. background: #f4f4f4 url(docs/images/background.png);
  13. }
  14. .interface {
  15. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  16. }
  17. div#sidebar {
  18. background: #fff;
  19. position: fixed;
  20. top: 0; left: 0; bottom: 0;
  21. width: 200px;
  22. overflow-y: auto;
  23. overflow-x: hidden;
  24. padding: 15px 0 30px 30px;
  25. border-right: 1px solid #ddd;
  26. box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  27. }
  28. a.toc_title, a.toc_title:visited {
  29. display: block;
  30. color: black;
  31. font-weight: bold;
  32. margin-top: 15px;
  33. }
  34. a.toc_title:hover {
  35. text-decoration: underline;
  36. }
  37. #sidebar .version {
  38. font-size: 10px;
  39. font-weight: normal;
  40. }
  41. ul.toc_section {
  42. font-size: 11px;
  43. line-height: 14px;
  44. margin: 5px 0 0 0;
  45. padding-left: 0px;
  46. list-style-type: none;
  47. font-family: Lucida Grande;
  48. }
  49. .toc_section li {
  50. cursor: pointer;
  51. margin: 0 0 3px 0;
  52. }
  53. .toc_section li a {
  54. text-decoration: none;
  55. color: black;
  56. }
  57. .toc_section li a:hover {
  58. text-decoration: underline;
  59. }
  60. div.container {
  61. position: relative;
  62. width: 550px;
  63. margin: 40px 0 50px 260px;
  64. }
  65. div.run {
  66. position: absolute;
  67. right: 15px;
  68. width: 26px; height: 18px;
  69. background: url('docs/images/arrows.png') no-repeat -26px 0;
  70. }
  71. div.run:active {
  72. background-position: -51px 0;
  73. }
  74. p, div.container ul {
  75. margin: 20px 0;
  76. width: 550px;
  77. }
  78. p.warning {
  79. font-size: 12px;
  80. line-height: 18px;
  81. font-style: italic;
  82. }
  83. div.container ul {
  84. list-style: circle;
  85. font-size: 12px;
  86. padding-left: 15px;
  87. }
  88. a, a:visited {
  89. color: #444;
  90. }
  91. a:active, a:hover {
  92. color: #000;
  93. }
  94. a img {
  95. border: 0;
  96. }
  97. h1, h2, h3, h4, h5, h6 {
  98. padding-top: 20px;
  99. }
  100. h2 {
  101. font-size: 20px;
  102. }
  103. b.header {
  104. font-size: 16px;
  105. line-height: 30px;
  106. }
  107. span.alias {
  108. font-size: 14px;
  109. font-style: italic;
  110. margin-left: 20px;
  111. }
  112. table {
  113. margin: 15px 0 0; padding: 0;
  114. }
  115. tr, td {
  116. margin: 0; padding: 0;
  117. }
  118. td {
  119. padding: 0px 15px 5px 0;
  120. }
  121. code, pre, tt {
  122. font-family: Monaco, Consolas, "Lucida Console", monospace;
  123. font-size: 12px;
  124. line-height: 18px;
  125. font-style: normal;
  126. }
  127. tt {
  128. padding: 0px 3px;
  129. background: #fff;
  130. border: 1px solid #ddd;
  131. zoom: 1;
  132. }
  133. code {
  134. margin-left: 20px;
  135. }
  136. pre {
  137. font-size: 12px;
  138. padding: 2px 0 2px 15px;
  139. border: 4px solid #bbb; border-top: 0; border-bottom: 0;
  140. margin: 0px 0 30px;
  141. }
  142. img.example_image {
  143. margin: 0px auto;
  144. }
  145. </style>
  146. </head>
  147. <body>
  148. <div id="sidebar" class="interface">
  149. <a class="toc_title" href="#">
  150. Backbone.js <span class="version">(0.5.3)</span>
  151. </a>
  152. <a class="toc_title" href="#Introduction">
  153. Introduction
  154. </a>
  155. <a class="toc_title" href="#Events">
  156. Events
  157. </a>
  158. <ul class="toc_section">
  159. <li> <a href="#Events-bind">bind</a></li>
  160. <li> <a href="#Events-unbind">unbind</a></li>
  161. <li> <a href="#Events-trigger">trigger</a></li>
  162. </ul>
  163. <a class="toc_title" href="#Model">
  164. Model
  165. </a>
  166. <ul class="toc_section">
  167. <li> <a href="#Model-extend">extend</a></li>
  168. <li> <a href="#Model-constructor">constructor / initialize</a></li>
  169. <li> <a href="#Model-get">get</a></li>
  170. <li> <a href="#Model-set">set</a></li>
  171. <li> <a href="#Model-escape">escape</a></li>
  172. <li> <a href="#Model-has">has</a></li>
  173. <li> <a href="#Model-unset">unset</a></li>
  174. <li> <a href="#Model-clear">clear</a></li>
  175. <li> <a href="#Model-id">id</a></li>
  176. <li> <a href="#Model-cid">cid</a></li>
  177. <li> <a href="#Model-attributes">attributes</a></li>
  178. <li> <a href="#Model-defaults">defaults</a></li>
  179. <li>- <a href="#Model-toJSON">toJSON</a></li>
  180. <li> <a href="#Model-fetch">fetch</a></li>
  181. <li> <a href="#Model-save">save</a></li>
  182. <li> <a href="#Model-destroy">destroy</a></li>
  183. <li> <a href="#Model-validate">validate</a></li>
  184. <li> <a href="#Model-url">url</a></li>
  185. <li> <a href="#Model-urlRoot">urlRoot</a></li>
  186. <li> <a href="#Model-parse">parse</a></li>
  187. <li> <a href="#Model-clone">clone</a></li>
  188. <li> <a href="#Model-isNew">isNew</a></li>
  189. <li> <a href="#Model-change">change</a></li>
  190. <li> <a href="#Model-hasChanged">hasChanged</a></li>
  191. <li> <a href="#Model-changedAttributes">changedAttributes</a></li>
  192. <li> <a href="#Model-previous">previous</a></li>
  193. <li> <a href="#Model-previousAttributes">previousAttributes</a></li>
  194. </ul>
  195. <a class="toc_title" href="#Collection">
  196. Collection
  197. </a>
  198. <ul class="toc_section">
  199. <li> <a href="#Collection-extend">extend</a></li>
  200. <li> <a href="#Collection-model">model</a></li>
  201. <li> <a href="#Collection-constructor">constructor / initialize</a></li>
  202. <li> <a href="#Collection-models">models</a></li>
  203. <li> <a href="#Collection-toJSON">toJSON</a></li>
  204. <li> <a href="#Collection-Underscore-Methods"><b>Underscore Methods (26)</b></a></li>
  205. <li> <a href="#Collection-add">add</a></li>
  206. <li> <a href="#Collection-remove">remove</a></li>
  207. <li> <a href="#Collection-get">get</a></li>
  208. <li> <a href="#Collection-getByCid">getByCid</a></li>
  209. <li> <a href="#Collection-at">at</a></li>
  210. <li> <a href="#Collection-length">length</a></li>
  211. <li> <a href="#Collection-comparator">comparator</a></li>
  212. <li> <a href="#Collection-sort">sort</a></li>
  213. <li> <a href="#Collection-pluck">pluck</a></li>
  214. <li> <a href="#Collection-url">url</a></li>
  215. <li> <a href="#Collection-parse">parse</a></li>
  216. <li> <a href="#Collection-fetch">fetch</a></li>
  217. <li> <a href="#Collection-reset">reset</a></li>
  218. <li> <a href="#Collection-create">create</a></li>
  219. </ul>
  220. <a class="toc_title" href="#Router">
  221. Router
  222. </a>
  223. <ul class="toc_section">
  224. <li> <a href="#Router-extend">extend</a></li>
  225. <li> <a href="#Router-routes">routes</a></li>
  226. <li> <a href="#Router-constructor">constructor / initialize</a></li>
  227. <li> <a href="#Router-route">route</a></li>
  228. <li> <a href="#Router-navigate">navigate</a></li>
  229. </ul>
  230. <a class="toc_title" href="#History">
  231. History
  232. </a>
  233. <ul class="toc_section">
  234. <li> <a href="#History-start">start</a></li>
  235. </ul>
  236. <a class="toc_title" href="#Sync">
  237. Sync
  238. </a>
  239. <ul class="toc_section">
  240. <li> <a href="#Sync">Backbone.sync</a></li>
  241. <li> <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
  242. <li> <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
  243. </ul>
  244. <a class="toc_title" href="#View">
  245. View
  246. </a>
  247. <ul class="toc_section">
  248. <li> <a href="#View-extend">extend</a></li>
  249. <li> <a href="#View-constructor">constructor / initialize</a></li>
  250. <li> <a href="#View-el">el</a></li>
  251. <li> <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
  252. <li> <a href="#View-render">render</a></li>
  253. <li> <a href="#View-remove">remove</a></li>
  254. <li> <a href="#View-make">make</a></li>
  255. <li> <a href="#View-delegateEvents">delegateEvents</a></li>
  256. </ul>
  257. <a class="toc_title" href="#Utility">
  258. Utility
  259. </a>
  260. <ul class="toc_section">
  261. <li> <a href="#Utility-noConflict">noConflict</a></li>
  262. </ul>
  263. <a class="toc_title" href="#examples">
  264. Examples
  265. </a>
  266. <ul class="toc_section">
  267. <li> <a href="#examples-todos">Todos</a></li>
  268. <li> <a href="#examples-documentcloud">DocumentCloud</a></li>
  269. <li> <a href="#examples-basecamp">Basecamp Mobile</a></li>
  270. <li> <a href="#examples-flow">Flow</a></li>
  271. <li> <a href="#examples-groupon">Groupon Now!</a></li>
  272. <li> <a href="#examples-trajectory">Trajectory</a></li>
  273. <li> <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
  274. <li> <a href="#examples-pandora">Pandora</a></li>
  275. <li> <a href="#examples-cloudapp">CloudApp</a></li>
  276. <li> <a href="#examples-seatgeek">SeatGeek</a></li>
  277. <li> <a href="#examples-tpm">Talking Points Memo</a></li>
  278. <li> <a href="#examples-hotel-tonight">Hotel Tonight</a></li>
  279. <li> <a href="#examples-quoteroller">Quote Roller</a></li>
  280. <li> <a href="#examples-tilemill">TileMill</a></li>
  281. <li> <a href="#examples-menagerievet">Menagerie Whiteboard</a></li>
  282. <li>- <a href="#examples-blossom">Blossom</a></li>
  283. <li>- <a href="#examples-instagreat">Insta-great!</a></li>
  284. <li>- <a href="#examples-decide">Decide</a></li>
  285. <li>- <a href="#examples-bittorrent">BitTorrent</a></li>
  286. <li>- <a href="#examples-trapit">Trapit</a></li>
  287. <li>- <a href="#examples-fluxiom">Fluxiom</a></li>
  288. <li>- <a href="#examples-chop">Chop</a></li>
  289. <li>- <a href="#examples-test-kitchen">America&rsquo;s Test Kitchen</a></li>
  290. <li>- <a href="#examples-quietwrite">QuietWrite</a></li>
  291. <li>- <a href="#examples-tzigla">Tzigla</a></li>
  292. <li>- <a href="#examples-substance">Substance</a></li>
  293. </ul>
  294. <a class="toc_title" href="#faq">
  295. F.A.Q.
  296. </a>
  297. <ul class="toc_section">
  298. <li> <a href="#FAQ-events">Catalog of Events</a></li>
  299. <li> <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
  300. <li> <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
  301. <li> <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
  302. <li> <a href="#FAQ-mvc">Traditional MVC</a></li>
  303. <li> <a href="#FAQ-this">Binding "this"</a></li>
  304. </ul>
  305. <a class="toc_title" href="#changelog">
  306. Change Log
  307. </a>
  308. </div>
  309. <div class="container">
  310. <p>
  311. <img style="width: 385px; height: 126px;" src="docs/images/backbone.png" alt="Backbone.js" />
  312. </p>
  313. <p>
  314. <a href="http://github.com/documentcloud/backbone/">Backbone</a>
  315. supplies structure to JavaScript-heavy applications by providing <b>models</b> with
  316. key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
  317. <b>views</b> with declarative event handling, and connects it all to your
  318. existing application over a RESTful JSON interface.
  319. </p>
  320. <p>
  321. The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
  322. and the <a href="docs/backbone.html">annotated source code</a> is available,
  323. as well as an online <a href="test/test.html">test suite</a>, an
  324. <a href="examples/todos/index.html">example application</a> and a
  325. <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>.
  326. </p>
  327. <p>
  328. You can report bugs and discuss features on the
  329. <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
  330. on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
  331. <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
  332. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  333. </p>
  334. <p>
  335. <i>
  336. Backbone is an open-source component of
  337. <a href="http://documentcloud.org/">DocumentCloud</a>.
  338. </i>
  339. </p>
  340. <h2 id="downloads">
  341. Downloads &amp; Dependencies
  342. <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
  343. </h2>
  344. <table>
  345. <tr>
  346. <td><a href="backbone.js">Development Version (0.5.3)</a></td>
  347. <td><i>41kb, Full Source with Comments</i></td>
  348. </tr>
  349. <tr>
  350. <td><a href="backbone-min.js">Production Version (0.5.3)</a></td>
  351. <td><i>4.6kb, Packed and Gzipped</i></td>
  352. </tr>
  353. </table>
  354. <p>
  355. Backbone's only hard dependency is
  356. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
  357. For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
  358. and DOM manipulation with <a href="#View">Backbone.View</a>, include
  359. <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
  360. <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or
  361. <a href="http://zeptojs.com/">Zepto</a>.
  362. </p>
  363. <h2 id="Upgrading">Upgrading to 0.5.0+</h2>
  364. <p>
  365. We've taken the opportunity to clarify some naming with the <b>0.5.0</b>
  366. release. <tt>Controller</tt> is now <a href="#Router">Router</a>, and
  367. <tt>refresh</tt> is now <a href="#Collection-reset">reset</a>.
  368. The previous <tt>saveLocation</tt> and <tt>setLocation</tt>
  369. functions have been replaced by <a href="#Router-navigate">navigate</a>.
  370. <tt>Backbone.sync</tt>'s method signature has changed to allow the passing
  371. of arbitrary options to <tt>jQuery.ajax</tt>.
  372. Be sure to <a href="#History-start">opt-in</a> to <tt>pushState</tt> support,
  373. if you want to use it.
  374. </p>
  375. <h2 id="Introduction">Introduction</h2>
  376. <p>
  377. When working on a web application that involves a lot of JavaScript, one
  378. of the first things you learn is to stop tying your data to the DOM. It's all
  379. too easy to create JavaScript applications that end up as tangled piles of
  380. jQuery selectors and callbacks, all trying frantically to keep data in
  381. sync between the HTML UI, your JavaScript logic, and the database on your
  382. server. For rich client-side applications, a more structured approach
  383. is often helpful.
  384. </p>
  385. <p>
  386. With Backbone, you represent your data as
  387. <a href="#Model">Models</a>, which can be created, validated, destroyed,
  388. and saved to the server. Whenever a UI action causes an attribute of
  389. a model to change, the model triggers a <i>"change"</i> event; all
  390. the <a href="#View">Views</a> that display the model's data are notified of the
  391. event, causing them to re-render. You don't have to write the glue
  392. code that looks into the DOM to find an element with a specific <i>id</i>,
  393. and update the HTML manually
  394. &mdash; when the model changes, the views simply update themselves.
  395. </p>
  396. <p>
  397. Many of the examples that follow are runnable. Click the <i>play</i> button
  398. to execute them.
  399. </p>
  400. <h2 id="Events">Backbone.Events</h2>
  401. <p>
  402. <b>Events</b> is a module that can be mixed in to any object, giving the
  403. object the ability to bind and trigger custom named events. Events do not
  404. have to be declared before they are bound, and may take passed arguments.
  405. For example:
  406. </p>
  407. <pre class="runnable">
  408. var object = {};
  409. _.extend(object, Backbone.Events);
  410. object.bind("alert", function(msg) {
  411. alert("Triggered " + msg);
  412. });
  413. object.trigger("alert", "an event");
  414. </pre>
  415. <p id="Events-bind">
  416. <b class="header">bind</b><code>object.bind(event, callback, [context])</code>
  417. <br />
  418. Bind a <b>callback</b> function to an object. The callback will be invoked
  419. whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
  420. If you have a large number of different events on a page, the convention is to use colons to
  421. namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
  422. </p>
  423. <p>
  424. To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
  425. pass the optional third argument: <tt>model.bind('change', this.render, this)</tt>
  426. </p>
  427. <p>
  428. Callbacks bound to the special
  429. <tt>"all"</tt> event will be triggered when any event occurs, and are passed
  430. the name of the event as the first argument. For example, to proxy all events
  431. from one object to another:
  432. </p>
  433. <pre>
  434. proxy.bind("all", function(eventName) {
  435. object.trigger(eventName);
  436. });
  437. </pre>
  438. <p id="Events-unbind">
  439. <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
  440. <br />
  441. Remove a previously-bound <b>callback</b> function from an object. If no
  442. callback is specified, all callbacks for the <b>event</b> will be
  443. removed. If no event is specified, <i>all</i> event callbacks on the object
  444. will be removed.
  445. </p>
  446. <pre>
  447. object.unbind("change", onChange); // Removes just the onChange callback.
  448. object.unbind("change"); // Removes all "change" callbacks.
  449. object.unbind(); // Removes all callbacks on object.
  450. </pre>
  451. <p id="Events-trigger">
  452. <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
  453. <br />
  454. Trigger callbacks for the given <b>event</b>. Subsequent arguments to
  455. <b>trigger</b> will be passed along to the event callbacks.
  456. </p>
  457. <h2 id="Model">Backbone.Model</h2>
  458. <p>
  459. <b>Models</b> are the heart of any JavaScript application, containing
  460. the interactive data as well as a large part of the logic surrounding it:
  461. conversions, validations, computed properties, and access control. You
  462. extend <b>Backbone.Model</b> with your domain-specific methods, and
  463. <b>Model</b> provides a basic set of functionality for managing changes.
  464. </p>
  465. <p>
  466. The following is a contrived example, but it demonstrates defining a model
  467. with a custom method, setting an attribute, and firing an event keyed
  468. to changes in that specific attribute.
  469. After running this code once, <tt>sidebar</tt> will be
  470. available in your browser's console, so you can play around with it.
  471. </p>
  472. <pre class="runnable">
  473. var Sidebar = Backbone.Model.extend({
  474. promptColor: function() {
  475. var cssColor = prompt("Please enter a CSS color:");
  476. this.set({color: cssColor});
  477. }
  478. });
  479. window.sidebar = new Sidebar;
  480. sidebar.bind('change:color', function(model, color) {
  481. $('#sidebar').css({background: color});
  482. });
  483. sidebar.set({color: 'white'});
  484. sidebar.promptColor();
  485. </pre>
  486. <p id="Model-extend">
  487. <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
  488. <br />
  489. To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
  490. and provide instance <b>properties</b>, as well as optional
  491. <b>classProperties</b> to be attached directly to the constructor function.
  492. </p>
  493. <p>
  494. <b>extend</b> correctly sets up the prototype chain, so subclasses created
  495. with <b>extend</b> can be further extended and subclassed as far as you like.
  496. </p>
  497. <pre>
  498. var Note = Backbone.Model.extend({
  499. initialize: function() { ... },
  500. author: function() { ... },
  501. coordinates: function() { ... },
  502. allowedToEdit: function(account) {
  503. return true;
  504. }
  505. });
  506. var PrivateNote = Note.extend({
  507. allowedToEdit: function(account) {
  508. return account.owns(this);
  509. }
  510. });
  511. </pre>
  512. <p class="warning">
  513. Brief aside on <tt>super</tt>: JavaScript does not provide
  514. a simple way to call super &mdash; the function of the same name defined
  515. higher on the prototype chain. If you override a core function like
  516. <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
  517. parent object's implementation, you'll have to explicitly call it, along these lines:
  518. </p>
  519. <pre>
  520. var Note = Backbone.Model.extend({
  521. set: function(attributes, options) {
  522. Backbone.Model.prototype.set.call(this, attributes, options);
  523. ...
  524. }
  525. });
  526. </pre>
  527. <p id="Model-constructor">
  528. <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
  529. <br />
  530. When creating an instance of a model, you can pass in the initial values
  531. of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
  532. model. If you define an <b>initialize</b> function, it will be invoked when
  533. the model is created.
  534. </p>
  535. <pre>
  536. new Book({
  537. title: "One Thousand and One Nights",
  538. author: "Scheherazade"
  539. });
  540. </pre>
  541. <p id="Model-get">
  542. <b class="header">get</b><code>model.get(attribute)</code>
  543. <br />
  544. Get the current value of an attribute from the model. For example:
  545. <tt>note.get("title")</tt>
  546. </p>
  547. <p id="Model-set">
  548. <b class="header">set</b><code>model.set(attributes, [options])</code>
  549. <br />
  550. Set a hash of attributes (one or many) on the model. If any of the attributes
  551. change the models state, a <tt>"change"</tt> event will be triggered, unless
  552. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  553. attributes are also triggered, and you can bind to those as well, for example:
  554. <tt>change:title</tt>, and <tt>change:content</tt>.
  555. </p>
  556. <pre>
  557. note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
  558. </pre>
  559. <p>
  560. If the model has a <a href="#Model-validate">validate</a> method,
  561. it will be validated before the attributes are set, no changes will
  562. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  563. You may also pass an <tt>error</tt>
  564. callback in the options, which will be invoked instead of triggering an
  565. <tt>"error"</tt> event, should validation fail.
  566. </p>
  567. <p id="Model-escape">
  568. <b class="header">escape</b><code>model.escape(attribute)</code>
  569. <br />
  570. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  571. of a model's attribute. If you're interpolating data from the model into
  572. HTML, using <b>escape</b> to retrieve attributes will prevent
  573. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  574. </p>
  575. <pre class="runnable">
  576. var hacker = new Backbone.Model({
  577. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  578. });
  579. alert(hacker.escape('name'));
  580. </pre>
  581. <p id="Model-has">
  582. <b class="header">has</b><code>model.has(attribute)</code>
  583. <br />
  584. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  585. value.
  586. </p>
  587. <pre>
  588. if (note.has("title")) {
  589. ...
  590. }
  591. </pre>
  592. <p id="Model-unset">
  593. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  594. <br />
  595. Remove an attribute by deleting it from the internal attributes hash.
  596. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  597. </p>
  598. <p id="Model-clear">
  599. <b class="header">clear</b><code>model.clear([options])</code>
  600. <br />
  601. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  602. <tt>silent</tt> is passed as an option.
  603. </p>
  604. <p id="Model-id">
  605. <b class="header">id</b><code>model.id</code>
  606. <br />
  607. A special property of models, the <b>id</b> is an arbitrary string
  608. (integer id or UUID). If you set the <b>id</b> in the
  609. attributes hash, it will be copied onto the model as a direct property.
  610. Models can be retrieved by id from collections, and the id is used to generate
  611. model URLs by default.
  612. </p>
  613. <p id="Model-cid">
  614. <b class="header">cid</b><code>model.cid</code>
  615. <br />
  616. A special property of models, the <b>cid</b> or client id is a unique identifier
  617. automatically assigned to all models when they're first created. Client ids
  618. are handy when the model has not yet been saved to the server, and does not
  619. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  620. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  621. </p>
  622. <p id="Model-attributes">
  623. <b class="header">attributes</b><code>model.attributes</code>
  624. <br />
  625. The <b>attributes</b> property is the internal hash containing the model's
  626. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  627. them directly. If you'd like to retrieve and munge a copy of the model's
  628. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  629. </p>
  630. <p id="Model-defaults">
  631. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  632. <br />
  633. The <b>defaults</b> hash (or function) can be used to specify the default
  634. attributes for your model. When creating an instance of the model,
  635. any unspecified attributes will be set to their default value.
  636. </p>
  637. <pre class="runnable">
  638. var Meal = Backbone.Model.extend({
  639. defaults: {
  640. "appetizer": "caesar salad",
  641. "entree": "ravioli",
  642. "dessert": "cheesecake"
  643. }
  644. });
  645. alert("Dessert will be " + (new Meal).get('dessert'));
  646. </pre>
  647. <p class="warning">
  648. Remember that in JavaScript, objects are passed by reference, so if you
  649. include an object as a default value, it will be shared among all instances.
  650. </p>
  651. <p id="Model-toJSON">
  652. <b class="header">toJSON</b><code>model.toJSON()</code>
  653. <br />
  654. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  655. This can be used for persistence, serialization, or for augmentation before
  656. being handed off to a view. The name of this method is a bit confusing, as
  657. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  658. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  659. </p>
  660. <pre class="runnable">
  661. var artist = new Backbone.Model({
  662. firstName: "Wassily",
  663. lastName: "Kandinsky"
  664. });
  665. artist.set({birthday: "December 16, 1866"});
  666. alert(JSON.stringify(artist));
  667. </pre>
  668. <p id="Model-fetch">
  669. <b class="header">fetch</b><code>model.fetch([options])</code>
  670. <br />
  671. Resets the model's state from the server. Useful if the model has never
  672. been populated with data, or if you'd like to ensure that you have the
  673. latest server state. A <tt>"change"</tt> event will be triggered if the
  674. server's state differs from the current attributes. Accepts
  675. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  676. are passed <tt>(model, response)</tt> as arguments.
  677. </p>
  678. <pre>
  679. // Poll every 10 seconds to keep the channel model up-to-date.
  680. setInterval(function() {
  681. channel.fetch();
  682. }, 10000);
  683. </pre>
  684. <p id="Model-save">
  685. <b class="header">save</b><code>model.save([attributes], [options])</code>
  686. <br />
  687. Save a model to your database (or alternative persistence layer),
  688. by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
  689. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  690. you'd like to change -- keys that aren't mentioned won't be altered.
  691. If the model has a <a href="#Model-validate">validate</a>
  692. method, and validation fails, the model will not be saved. If the model
  693. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  694. (HTTP <tt>POST</tt>), if the model already
  695. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  696. </p>
  697. <p>
  698. In the following example, notice how our overridden version
  699. of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
  700. the first time the model is saved and an <tt>"update"</tt>
  701. request the second time.
  702. </p>
  703. <pre class="runnable">
  704. Backbone.sync = function(method, model) {
  705. alert(method + ": " + JSON.stringify(model));
  706. model.id = 1;
  707. };
  708. var book = new Backbone.Model({
  709. title: "The Rough Riders",
  710. author: "Theodore Roosevelt"
  711. });
  712. book.save();
  713. book.save({author: "Teddy"});
  714. </pre>
  715. <p>
  716. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  717. options hash, which are passed <tt>(model, response)</tt> as arguments.
  718. The <tt>error</tt> callback will also be invoked if the model has a
  719. <tt>validate</tt> method, and validation fails. If a server-side
  720. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  721. an error response in text or JSON.
  722. </p>
  723. <pre>
  724. book.save({author: "F.D.R."}, {error: function(){ ... }});
  725. </pre>
  726. <p id="Model-destroy">
  727. <b class="header">destroy</b><code>model.destroy([options])</code>
  728. <br />
  729. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  730. request to <a href="#Sync">Backbone.sync</a>. Accepts
  731. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  732. Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
  733. through any collections that contain it.
  734. </p>
  735. <pre>
  736. book.destroy({success: function(model, response) {
  737. ...
  738. }});
  739. </pre>
  740. <p id="Model-validate">
  741. <b class="header">validate</b><code>model.validate(attributes)</code>
  742. <br />
  743. This method is left undefined, and you're encouraged to override it with
  744. your custom validation logic, if you have any that can be performed
  745. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  746. <tt>save</tt>, and is passed the attributes that are about to be updated.
  747. If the model and attributes are valid, don't return anything from <b>validate</b>;
  748. if the attributes are invalid, return an error of your choosing. It
  749. can be as simple as a string error message to be displayed, or a complete
  750. error object that describes the error programmatically. <tt>set</tt> and
  751. <tt>save</tt> will not continue if <b>validate</b> returns an error.
  752. Failed validations trigger an <tt>"error"</tt> event.
  753. </p>
  754. <pre class="runnable">
  755. var Chapter = Backbone.Model.extend({
  756. validate: function(attrs) {
  757. if (attrs.end < attrs.start) {
  758. return "can't end before it starts";
  759. }
  760. }
  761. });
  762. var one = new Chapter({
  763. title : "Chapter One: The Beginning"
  764. });
  765. one.bind("error", function(model, error) {
  766. alert(model.get("title") + " " + error);
  767. });
  768. one.set({
  769. start: 15,
  770. end: 10
  771. });
  772. </pre>
  773. <p>
  774. <tt>"error"</tt> events are useful for providing coarse-grained error
  775. messages at the model or collection level, but if you have a specific view
  776. that can better handle the error, you may override and suppress the event
  777. by passing an <tt>error</tt> callback directly:
  778. </p>
  779. <pre>
  780. account.set({access: "unlimited"}, {
  781. error: function(model, error) {
  782. alert(error);
  783. }
  784. });
  785. </pre>
  786. <p id="Model-url">
  787. <b class="header">url</b><code>model.url()</code>
  788. <br />
  789. Returns the relative URL where the model's resource would be located on
  790. the server. If your models are located somewhere else, override this method
  791. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  792. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  793. </p>
  794. <p>
  795. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  796. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  797. property, if all models of this class share a common root URL.
  798. A model with an id of <tt>101</tt>, stored in a
  799. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  800. would have this URL: <tt>"/documents/7/notes/101"</tt>
  801. </p>
  802. <p id="Model-urlRoot">
  803. <b class="header">urlRoot</b><code>model.urlRoot</code>
  804. <br />
  805. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  806. to enable the default <a href="#Model-url">url</a> function to generate
  807. URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
  808. </p>
  809. <pre class="runnable">
  810. var Book = Backbone.Model.extend({urlRoot : '/books'});
  811. var solaris = new Book({id: "1083-lem-solaris"});
  812. alert(solaris.url());
  813. </pre>
  814. <p id="Model-parse">
  815. <b class="header">parse</b><code>model.parse(response)</code>
  816. <br />
  817. <b>parse</b> is called whenever a model's data is returned by the
  818. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  819. The function is passed the raw <tt>response</tt> object, and should return
  820. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  821. default implementation is a no-op, simply passing through the JSON response.
  822. Override this if you need to work with a preexisting API, or better namespace
  823. your responses.
  824. </p>
  825. <p>
  826. If you're working with a Rails backend, you'll notice that Rails' default
  827. <tt>to_json</tt> implementation includes a model's attributes under a
  828. namespace. To disable this behavior for seamless Backbone integration, set:
  829. </p>
  830. <pre>
  831. ActiveRecord::Base.include_root_in_json = false
  832. </pre>
  833. <p id="Model-clone">
  834. <b class="header">clone</b><code>model.clone()</code>
  835. <br />
  836. Returns a new instance of the model with identical attributes.
  837. </p>
  838. <p id="Model-isNew">
  839. <b class="header">isNew</b><code>model.isNew()</code>
  840. <br />
  841. Has this model been saved to the server yet? If the model does not yet have
  842. an <tt>id</tt>, it is considered to be new.
  843. </p>
  844. <p id="Model-change">
  845. <b class="header">change</b><code>model.change()</code>
  846. <br />
  847. Manually trigger the <tt>"change"</tt> event.
  848. If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  849. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  850. when you're all finished.
  851. </p>
  852. <p id="Model-hasChanged">
  853. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  854. <br />
  855. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  856. is passed, returns <tt>true</tt> if that specific attribute has changed.
  857. </p>
  858. <p class="warning">
  859. Note that this method, and the following change-related ones,
  860. are only useful during the course of a <tt>"change"</tt> event.
  861. </p>
  862. <pre>
  863. book.bind("change", function() {
  864. if (book.hasChanged("title")) {
  865. ...
  866. }
  867. });
  868. </pre>
  869. <p id="Model-changedAttributes">
  870. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  871. <br />
  872. Retrieve a hash of only the model's attributes that have changed. Optionally,
  873. an external <b>attributes</b> hash can be passed in, returning
  874. the attributes in that hash which differ from the model. This can be used
  875. to figure out which portions of a view should be updated, or what calls
  876. need to be made to sync the changes to the server.
  877. </p>
  878. <p id="Model-previous">
  879. <b class="header">previous</b><code>model.previous(attribute)</code>
  880. <br />
  881. During a <tt>"change"</tt> event, this method can be used to get the
  882. previous value of a changed attribute.
  883. </p>
  884. <pre class="runnable">
  885. var bill = new Backbone.Model({
  886. name: "Bill Smith"
  887. });
  888. bill.bind("change:name", function(model, name) {
  889. alert("Changed name from " + bill.previous("name") + " to " + name);
  890. });
  891. bill.set({name : "Bill Jones"});
  892. </pre>
  893. <p id="Model-previousAttributes">
  894. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  895. <br />
  896. Return a copy of the model's previous attributes. Useful for getting a
  897. diff between versions of a model, or getting back to a valid state after
  898. an error occurs.
  899. </p>
  900. <h2 id="Collection">Backbone.Collection</h2>
  901. <p>
  902. Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
  903. to be notified when any model in the collection has been modified,
  904. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  905. the collection from the server, and use a full suite of
  906. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  907. </p>
  908. <p>
  909. Any event that is triggered on a model in a collection will also be
  910. triggered on the collection directly, for convenience.
  911. This allows you to listen for changes to specific attributes in any
  912. model in a collection, for example:
  913. <tt>Documents.bind("change:selected", ...)</tt>
  914. </p>
  915. <p id="Collection-extend">
  916. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  917. <br />
  918. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  919. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  920. directly to the collection's constructor function.
  921. </p>
  922. <p id="Collection-model">
  923. <b class="header">model</b><code>collection.model</code>
  924. <br />
  925. Override this property to specify the model class that the collection
  926. contains. If defined, you can pass raw attributes objects (and arrays) to
  927. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  928. and <a href="#Collection-reset">reset</a>, and the attributes will be
  929. converted into a model of the proper type.
  930. </p>
  931. <pre>
  932. var Library = Backbone.Collection.extend({
  933. model: Book
  934. });
  935. </pre>
  936. <p id="Collection-constructor">
  937. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  938. <br />
  939. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  940. The collection's <a href="#Collection-comparator">comparator</a> function
  941. may be included as an option. If you define an <b>initialize</b> function, it will be
  942. invoked when the collection is created.
  943. </p>
  944. <pre>
  945. var tabs = new TabSet([tab1, tab2, tab3]);
  946. </pre>
  947. <p id="Collection-models">
  948. <b class="header">models</b><code>collection.models</code>
  949. <br />
  950. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  951. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  952. to access model objects, but occasionally a direct reference to the array
  953. is desired.
  954. </p>
  955. <p id="Collection-toJSON">
  956. <b class="header">toJSON</b><code>collection.toJSON()</code>
  957. <br />
  958. Return an array containing the attributes hash of each model in the
  959. collection. This can be used to serialize and persist the
  960. collection as a whole. The name of this method is a bit confusing, because
  961. it conforms to
  962. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  963. </p>
  964. <pre class="runnable">
  965. var collection = new Backbone.Collection([
  966. {name: "Tim", age: 5},
  967. {name: "Ida", age: 26},
  968. {name: "Rob", age: 55}
  969. ]);
  970. alert(JSON.stringify(collection));
  971. </pre>
  972. <p id="Collection-Underscore-Methods">
  973. <b class="header">Underscore Methods (26)</b>
  974. <br />
  975. Backbone proxies to <b>Underscore.js</b> to provide 26 iteration functions
  976. on <b>Backbone.Collection</b>. They aren't all documented here, but
  977. you can take a look at the Underscore documentation for the full details&hellip;
  978. </p>
  979. <ul>
  980. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  981. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  982. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  983. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  984. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  985. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  986. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  987. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  988. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  989. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  990. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  991. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  992. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  993. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  994. <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li>
  995. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  996. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  997. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  998. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  999. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  1000. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  1001. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  1002. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  1003. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  1004. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  1005. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  1006. </ul>
  1007. <pre>
  1008. Books.each(function(book) {
  1009. book.publish();
  1010. });
  1011. var titles = Books.map(function(book) {
  1012. return book.get("title");
  1013. });
  1014. var publishedBooks = Books.filter(function(book) {
  1015. return book.get("published") === true;
  1016. });
  1017. var alphabetical = Books.sortBy(function(book) {
  1018. return book.author.get("name").toLowerCase();
  1019. });
  1020. </pre>
  1021. <p id="Collection-add">
  1022. <b class="header">add</b><code>collection.add(models, [options])</code>
  1023. <br />
  1024. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  1025. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  1026. <a href="#Collection-model">model</a> property is defined, you may also pass
  1027. raw attributes objects, and have them be vivified as instances of the model.
  1028. Pass <tt>{at: index}</tt> to splice the model into the collection at the
  1029. specified <tt>index</tt>.
  1030. </p>
  1031. <pre class="runnable">
  1032. var ships = new Backbone.Collection;
  1033. ships.bind("add", function(ship) {
  1034. alert("Ahoy " + ship.get("name") + "!");
  1035. });
  1036. ships.add([
  1037. {name: "Flying Dutchman"},
  1038. {name: "Black Pearl"}
  1039. ]);
  1040. </pre>
  1041. <p id="Collection-remove">
  1042. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  1043. <br />
  1044. Remove a model (or an array of models) from the collection. Fires a
  1045. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  1046. to suppress.
  1047. </p>
  1048. <p id="Collection-get">
  1049. <b class="header">get</b><code>collection.get(id)</code>
  1050. <br />
  1051. Get a model from a collection, specified by <b>id</b>.
  1052. </p>
  1053. <pre>
  1054. var book = Library.get(110);
  1055. </pre>
  1056. <p id="Collection-getByCid">
  1057. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  1058. <br />
  1059. Get a model from a collection, specified by client id. The client id
  1060. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  1061. a model is created. Useful for models which have not yet been saved to
  1062. the server, and do not yet have true ids.
  1063. </p>
  1064. <p id="Collection-at">
  1065. <b class="header">at</b><code>collection.at(index)</code>
  1066. <br />
  1067. Get a model from a collection, specified by index. Useful if your collection
  1068. is sorted, and if your collection isn't sorted, <b>at</b> will still
  1069. retrieve models in insertion order.
  1070. </p>
  1071. <p id="Collection-length">
  1072. <b class="header">length</b><code>collection.length</code>
  1073. <br />
  1074. Like an array, a Collection maintains a <tt>length</tt> property, counting
  1075. the number of models it contains.
  1076. </p>
  1077. <p id="Collection-comparator">
  1078. <b class="header">comparator</b><code>collection.comparator</code>
  1079. <br />
  1080. By default there is no <b>comparator</b> function on a collection.
  1081. If you define a comparator, it will be used to maintain
  1082. the collection in sorted order. This means that as models are added,
  1083. they are inserted at the correct index in <tt>collection.models</tt>.
  1084. Comparator functions take a model and return a numeric or string value
  1085. by which the model should be ordered relative to others.
  1086. </p>
  1087. <p>
  1088. Note how even though all of the chapters in this example are added backwards,
  1089. they come out in the proper order:
  1090. </p>
  1091. <pre class="runnable">
  1092. var Chapter = Backbone.Model;
  1093. var chapters = new Backbone.Collection;
  1094. chapters.comparator = function(chapter) {
  1095. return chapter.get("page");
  1096. };
  1097. chapters.add(new Chapter({page: 9, title: "The End"}));
  1098. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1099. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1100. alert(chapters.pluck('title'));
  1101. </pre>
  1102. <p class="warning">
  1103. Brief aside: This comparator function is different than JavaScript's regular
  1104. "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
  1105. and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
  1106. </p>
  1107. <p id="Collection-sort">
  1108. <b class="header">sort</b><code>collection.sort([options])</code>
  1109. <br />
  1110. Force a collection to re-sort itself. You don't need to call this under
  1111. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1112. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1113. triggers the collection's <tt>"reset"</tt> event, unless silenced by passing
  1114. <tt>{silent: true}</tt>
  1115. </p>
  1116. <p id="Collection-pluck">
  1117. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1118. <br />
  1119. Pluck an attribute from each model in the collection. Equivalent to calling
  1120. <tt>map</tt>, and returning a single attribute from the iterator.
  1121. </p>
  1122. <pre class="runnable">
  1123. var stooges = new Backbone.Collection([
  1124. new Backbone.Model({name: "Curly"}),
  1125. new Backbone.Model({name: "Larry"}),
  1126. new Backbone.Model({name: "Moe"})
  1127. ]);
  1128. var names = stooges.pluck("name");
  1129. alert(JSON.stringify(names));
  1130. </pre>
  1131. <p id="Collection-url">
  1132. <b class="header">url</b><code>collection.url or collection.url()</code>
  1133. <br />
  1134. Set the <b>url</b> property (or function) on a collection to reference
  1135. its location on the server. Models within the collection will use <b>url</b>
  1136. to construct URLs of their own.
  1137. </p>
  1138. <pre>
  1139. var Notes = Backbone.Collection.extend({
  1140. url: '/notes'
  1141. });
  1142. // Or, something more sophisticated:
  1143. var Notes = Backbone.Collection.extend({
  1144. url: function() {
  1145. return this.document.url() + '/notes';
  1146. }
  1147. });
  1148. </pre>
  1149. <p id="Collection-parse">
  1150. <b class="header">parse</b><code>collection.parse(response)</code>
  1151. <br />
  1152. <b>parse</b> is called by Backbone whenever a collection's models are
  1153. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1154. The function is passed the raw <tt>response</tt> object, and should return
  1155. the array of model attributes to be <a href="#Collection-add">added</a>
  1156. to the collection. The default implementation is a no-op, simply passing
  1157. through the JSON response. Override this if you need to work with a
  1158. preexisting API, or better namespace your responses.
  1159. </p>
  1160. <pre>
  1161. var Tweets = Backbone.Collection.extend({
  1162. // The Twitter Search API returns tweets under "results".
  1163. parse: function(response) {
  1164. return response.results;
  1165. }
  1166. });
  1167. </pre>
  1168. <p id="Collection-fetch">
  1169. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1170. <br />
  1171. Fetch the default set of models for this collection from the server,
  1172. resetting the collection when they arrive. The <b>options</b> hash takes
  1173. <tt>success</tt> and <tt>error</tt>
  1174. callbacks which will be passed <tt>(collection, response)</tt> as arguments.
  1175. When the model data returns from the server, the collection will
  1176. <a href="#Collection-reset">reset</a>.
  1177. Delegates to <a href="#Sync">Backbone.sync</a>
  1178. under the covers, for custom persistence strategies.
  1179. The server handler for <b>fetch</b> requests should return a JSON array of
  1180. models.
  1181. </p>
  1182. <pre class="runnable">
  1183. Backbone.sync = function(method, model) {
  1184. alert(method + ": " + model.url);
  1185. };
  1186. var Accounts = new Backbone.Collection;
  1187. Accounts.url = '/accounts';
  1188. Accounts.fetch();
  1189. </pre>
  1190. <p>
  1191. If you'd like to add the incoming models to the current collection, instead
  1192. of replacing the collection's contents, pass <tt>{add: true}</tt> as an
  1193. option to <b>fetch</b>.
  1194. </p>
  1195. <p>
  1196. <b>jQuery.ajax</b> options can also be passed directly as <b>fetch</b> options,
  1197. so to fetch a specific page of a paginated collection:
  1198. <tt>Documents.fetch({data: {page: 3}})</tt>
  1199. </p>
  1200. <p>
  1201. Note that <b>fetch</b> should not be used to populate collections on
  1202. page load &mdash; all models needed at load time should already be
  1203. <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
  1204. intended for lazily-loading models for interfaces that are not needed
  1205. immediately: for example, documents with collections of notes that may be
  1206. toggled open and closed.
  1207. </p>
  1208. <p id="Collection-reset">
  1209. <b class="header">reset</b><code>collection.reset(models, [options])</code>
  1210. <br />
  1211. Adding and removing models one at a time is all well and good, but sometimes
  1212. you have so many models to change that you'd rather just update the collection
  1213. in bulk. Use <b>reset</b> to replace a collection with a new list
  1214. of models (or attribute hashes), triggering a single <tt>"reset"</tt> event
  1215. at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"reset"</tt> event.
  1216. Using reset with no arguments is useful as a way to empty the collection.
  1217. </p>
  1218. <p>
  1219. Here's an example using <b>reset</b> to bootstrap a collection during initial page load,
  1220. in a Rails application.
  1221. </p>
  1222. <pre>
  1223. &lt;script&gt;
  1224. Accounts.reset(&lt;%= @accounts.to_json %&gt;);
  1225. &lt;/script&gt;
  1226. </pre>
  1227. <p>
  1228. Calling <tt>collection.reset()</tt> without passing any models as arguments
  1229. will empty the entire collection.
  1230. </p>
  1231. <p id="Collection-create">
  1232. <b class="header">create</b><code>collection.create(attributes, [options])</code>
  1233. <br />
  1234. Convenience to create a new instance of a model within a collection.
  1235. Equivalent to instantiating a model with a hash of attributes,
  1236. saving the model to the server, and adding the model to the set after being
  1237. successfully created. Returns
  1238. the model, or <tt>false</tt> if a validation error prevented the
  1239. model from being created. In order for this to work, you should set the
  1240. <a href="#Collection-model">model</a> property of the collection.
  1241. The <b>create</b> method can accept either an attributes hash or an
  1242. existing, unsaved model object.
  1243. </p>
  1244. <pre>
  1245. var Library = Backbone.Collection.extend({
  1246. model: Book
  1247. });
  1248. var NYPL = new Library;
  1249. var othello = NYPL.create({
  1250. title: "Othello",
  1251. author: "William Shakespeare"
  1252. });
  1253. </pre>
  1254. <h2 id="Router">Backbone.Router</h2>
  1255. <p>
  1256. Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
  1257. in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
  1258. <b>Backbone.Router</b> provides methods for routing client-side URL
  1259. fragments, and connecting them to actions and events.
  1260. </p>
  1261. <p>
  1262. During page load, after your application has finished creating all of its routers,
  1263. be sure to call <tt>Backbone.history.start()</tt>, or
  1264. <tt>Backbone.history.start({pushState: true})</tt> to route the initial URL.
  1265. </p>
  1266. <p id="Router-extend">
  1267. <b class="header">extend</b><code>Backbone.Router.extend(properties, [classProperties])</code>
  1268. <br />
  1269. Get started by creating a custom router class. You'll
  1270. want to define actions that are triggered when certain URL fragments are
  1271. matched, and provide a <a href="#Router-routes">routes</a> hash
  1272. that pairs routes to actions.
  1273. </p>
  1274. <pre>
  1275. var Workspace = Backbone.Router.extend({
  1276. routes: {
  1277. "help": "help", // #help
  1278. "search/:query": "search", // #search/kiwis
  1279. "search/:query/p:page": "search" // #search/kiwis/p7
  1280. },
  1281. help: function() {
  1282. ...
  1283. },
  1284. search: function(query, page) {
  1285. ...
  1286. }
  1287. });
  1288. </pre>
  1289. <p id="Router-routes">
  1290. <b class="header">routes</b><code>router.routes</code>
  1291. <br />
  1292. The routes hash maps URLs with parameters to functions on your router,
  1293. similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
  1294. Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
  1295. component between slashes; and splat parts <tt>*splat</tt>, which can match
  1296. any number of URL components.
  1297. </p>
  1298. <p>
  1299. For example, a route of <tt>"search/:query/p:page"</tt> will match
  1300. a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
  1301. and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
  1302. match <tt>#file/nested/folder/file.txt</tt>,
  1303. passing <tt>"nested/folder/file.txt"</tt> to the action.
  1304. </p>
  1305. <p>
  1306. When the visitor presses the back button, or enters a URL, and a particular
  1307. route is matched, the name of the action will be fired as an
  1308. <a href="#Events">event</a>, so that other objects can listen to the router,
  1309. and be notified. In the following example, visiting <tt>#help/uploading</tt>
  1310. will fire a <tt>route:help</tt> event from the router.
  1311. </p>
  1312. <pre>
  1313. routes: {
  1314. "help/:page": "help",
  1315. "download/*path": "download",
  1316. "folder/:name": "openFolder",
  1317. "folder/:name-:mode": "openFolder"
  1318. }
  1319. </pre>
  1320. <pre>
  1321. router.bind("route:help", function(page) {
  1322. ...
  1323. });
  1324. </pre>
  1325. <p id="Router-constructor">
  1326. <b class="header">constructor / initialize</b><code>new Router([options])</code>
  1327. <br />
  1328. When creating a new router, you may pass its
  1329. <a href="#Router-routes">routes</a> hash directly as an option, if you
  1330. choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
  1331. function, if defined.
  1332. </p>
  1333. <p id="Router-route">
  1334. <b class="header">route</b><code>router.route(route, name, callback)</code>
  1335. <br />
  1336. Manually create a route for the router, The <tt>route</tt> argument may
  1337. be a <a href="#Router-routes">routing string</a> or regular expression.
  1338. Each matching capture from the route or regular expression will be passed as
  1339. an argument to the callback. The <tt>name</tt> argument will be triggered as
  1340. a <tt>"route:name"</tt> event whenever the route is matched.
  1341. </p>
  1342. <pre>
  1343. initialize: function(options) {
  1344. // Matches #page/10, passing "10"
  1345. this.route("page/:number", "page", function(number){ ... });
  1346. // Matches /117-a/b/c/open, passing "117-a/b/c"
  1347. this.route(/^(.*?)\/open$/, "open", function(id){ ... });
  1348. }
  1349. </pre>
  1350. <p id="Router-navigate">
  1351. <b class="header">navigate</b><code>router.navigate(fragment, [triggerRoute])</code>
  1352. <br />
  1353. Whenever you reach a point in your application that you'd like to save
  1354. as a URL, call <b>navigate</b> in order to update the URL.
  1355. If you wish to also call the route function, pass <b>triggerRoute</b>.
  1356. </p>
  1357. <pre>
  1358. openPage: function(pageNumber) {
  1359. this.document.pages.at(pageNumber).open();
  1360. this.navigate("page/" + pageNumber);
  1361. }
  1362. # Or ...
  1363. app.navigate("help/troubleshooting", true);
  1364. </pre>
  1365. <h2 id="History">Backbone.history</h2>
  1366. <p>
  1367. <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
  1368. events or <tt>pushState</tt>, match the appropriate route, and trigger callbacks. You shouldn't
  1369. ever have to create one of these yourself &mdash; you should use the reference
  1370. to <tt>Backbone.history</tt> that will be created for you automatically if you make use
  1371. of <a href="#Router">Routers</a> with <a href="#Router-routes">routes</a>.
  1372. </p>
  1373. <p>
  1374. <b>pushState</b> support exists on a purely opt-in basis in Backbone.
  1375. Older browsers that don't support <tt>pushState</tt> will continue to use
  1376. hash-based URL fragments, and if a hash URL is visited by a
  1377. <tt>pushState</tt>-capable browser, it will be transparently upgraded to
  1378. the true URL. Note that using real URLs requires your web server to be
  1379. able to correctly render those pages, so back-end changes are required
  1380. as well. For example, if you have a route of <tt>/documents/100</tt>,
  1381. your web server must be able to serve that page, if the browser
  1382. visits that URL directly. For full search-engine crawlability, it's best to
  1383. have the server generate the complete HTML for the page ... but if it's a web
  1384. application, just rendering the same content you would have for the root URL,
  1385. and filling in the rest with Backbone Views and JavaScript works fine.
  1386. </p>
  1387. <p id="History-start">
  1388. <b class="header">start</b><code>Backbone.history.start([options])</code>
  1389. <br />
  1390. When all of your <a href="#Router">Routers</a> have been created,
  1391. and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
  1392. to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
  1393. </p>
  1394. <p>
  1395. To indicate that you'd like to use HTML5 <tt>pushState</tt> support in
  1396. your application, use <tt>Backbone.history.start({pushState: true})</tt>.
  1397. </p>
  1398. <p>
  1399. If your application is not being served from the root url <tt>/</tt> of your
  1400. domain, be sure to tell History where the root really is, as an option:
  1401. <tt>Backbone.history.start({pushState: true, root: "/public/search/"})</tt>
  1402. </p>
  1403. <p>
  1404. When called, if a route succeeds with a match for the current URL,
  1405. <tt>Backbone.history.start()</tt> returns <tt>true</tt>. If no defined
  1406. route matches the current URL, it returns <tt>false</tt>.
  1407. </p>
  1408. <p>
  1409. If the server has already rendered the entire page, and you don't want the
  1410. initial route to trigger when starting History, pass <tt>silent: true</tt>.
  1411. </p>
  1412. <pre>
  1413. $(function(){
  1414. new WorkspaceRouter();
  1415. new HelpPaneRouter();
  1416. Backbone.history.start({pushState: true});
  1417. });
  1418. </pre>
  1419. <h2 id="Sync">Backbone.sync</h2>
  1420. <p>
  1421. <b>Backbone.sync</b> is the function that Backbone calls every time it
  1422. attempts to read or save a model to the server. By default, it uses
  1423. <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request. You can override
  1424. it in order to use a different persistence strategy, such as WebSockets,
  1425. XML transport, or Local Storage.
  1426. </p>
  1427. <p>
  1428. The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, [options])</tt>
  1429. </p>
  1430. <ul>
  1431. <li><b>method</b> the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
  1432. <li><b>model</b> the model to be saved (or collection to be read)</li>
  1433. <li><b>options</b> success and error callbacks, and all other jQuery request options</li>
  1434. </ul>
  1435. <p>
  1436. With the default implementation, when <b>Backbone.sync</b> sends up a request to save
  1437. a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
  1438. with content-type <tt>application/json</tt>. When returning a JSON response,
  1439. send down the attributes of the model that have been changed by the server, and need
  1440. to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
  1441. (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
  1442. of model attribute objects.
  1443. </p>
  1444. <p>
  1445. The default <b>sync</b> handler maps CRUD to REST like so:
  1446. </p>
  1447. <ul>
  1448. <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
  1449. <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
  1450. <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
  1451. <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
  1452. </ul>
  1453. <p>
  1454. As an example, a Rails handler responding to an <tt>"update"</tt> call from
  1455. <tt>Backbone</tt> might look like this: <i>(In real code, never use
  1456. </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
  1457. you allow to be changed.)</i>
  1458. </p>
  1459. <pre>
  1460. def update
  1461. account = Account.find params[:id]
  1462. account.update_attributes params
  1463. render :json => account
  1464. end
  1465. </pre>
  1466. <p>
  1467. One more tip for Rails integration is to disable the default namespacing for
  1468. <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
  1469. </p>
  1470. <p id="Sync-emulateHTTP">
  1471. <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
  1472. <br />
  1473. If you want to work with a legacy web server that doesn't support Backbones's
  1474. default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
  1475. Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
  1476. a HTTP <tt>POST</tt>, and pass them under the <tt>_method</tt> parameter. Setting this option
  1477. will also set an <tt>X-HTTP-Method-Override</tt> header with the true method.
  1478. </p>
  1479. <pre>
  1480. Backbone.emulateHTTP = true;
  1481. model.save(); // POST to "/collection/id", with "_method=PUT" + header.
  1482. </pre>
  1483. <p id="Sync-emulateJSON">
  1484. <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
  1485. <br />
  1486. If you're working with a legacy web server that can't handle requests
  1487. encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
  1488. will cause the JSON to be serialized under a <tt>model</tt> parameter, and
  1489. the request to be made with a <tt>application/x-www-form-urlencoded</tt>
  1490. mime type, as if from an HTML form.
  1491. </p>
  1492. <h2 id="View">Backbone.View</h2>
  1493. <p>
  1494. Backbone views are almost more convention than they are code &mdash; they
  1495. don't determine anything about your HTML or CSS for you, and can be used
  1496. with any JavaScript templating library.
  1497. The general idea is to organize your interface into logical views,
  1498. backed by models, each of which can be updated independently when the
  1499. model changes, without having to redraw the page. Instead of digging into
  1500. a JSON object, looking up an element in the DOM, and updating the HTML by hand,
  1501. you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
  1502. event &mdash; and now everywhere that
  1503. model data is displayed in the UI, it is always immediately up to date.
  1504. </p>
  1505. <p id="View-extend">
  1506. <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
  1507. <br />
  1508. Get started with views by creating a custom view class. You'll want to
  1509. override the <a href="#View-render">render</a> function, specify your
  1510. declarative <a href="#View-delegateEvents">events</a>, and perhaps the
  1511. <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
  1512. element.
  1513. </p>
  1514. <pre>
  1515. var DocumentRow = Backbone.View.extend({
  1516. tagName: "li",
  1517. className: "document-row",
  1518. events: {
  1519. "click .icon": "open",
  1520. "click .button.edit": "openEditDialog",
  1521. "click .button.delete": "destroy"
  1522. },
  1523. render: function() {
  1524. ...
  1525. }
  1526. });
  1527. </pre>
  1528. <p id="View-constructor">
  1529. <b class="header">constructor / initialize</b><code>new View([options])</code>
  1530. <br />
  1531. When creating a new View, the options you pass are attached to the view
  1532. as <tt>this.options</tt>, for future reference. There are several special
  1533. options that, if passed, will be attached directly to the view:
  1534. <tt>model</tt>, <tt>collection</tt>,
  1535. <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, and <tt>tagName</tt>.
  1536. If the view defines an <b>initialize</b> function, it will be called when
  1537. the view is first created. If you'd like to create a view that references
  1538. an element <i>already</i> in the DOM, pass in the element as an option:
  1539. <tt>new View({el: existingElement})</tt>
  1540. </p>
  1541. <pre>
  1542. var doc = Documents.first();
  1543. new DocumentRow({
  1544. model: doc,
  1545. id: "document-row-" + doc.id
  1546. });
  1547. </pre>
  1548. <p id="View-el">
  1549. <b class="header">el</b><code>view.el</code>
  1550. <br />
  1551. All views have a DOM element at all times (the <b>el</b> property),
  1552. whether they've already been inserted into the page or not. In this
  1553. fashion, views can be rendered at any time, and inserted into the DOM all
  1554. at once, in order to get high-performance UI rendering with as few
  1555. reflows and repaints as possible. <tt>this.el</tt> is created from the
  1556. view's <tt>tagName</tt>, <tt>className</tt>, and <tt>id</tt> properties,
  1557. if specified. If not, <b>el</b> is an empty <tt>div</tt>.
  1558. </p>
  1559. <p>
  1560. You may assign <b>el</b> directly if the view is being
  1561. created for an element that already exists in the DOM. Use either a
  1562. reference to a real DOM element, or a css selector string.
  1563. </p>
  1564. <pre class="runnable">
  1565. var ItemView = Backbone.View.extend({
  1566. tagName: 'li'
  1567. });
  1568. var BodyView = Backbone.View.extend({
  1569. el: 'body'
  1570. });
  1571. var item = new ItemView();
  1572. var body = new BodyView();
  1573. alert(item.el + ' ' + body.el);
  1574. </pre>
  1575. <p id="View-dollar">
  1576. <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
  1577. <br />
  1578. If jQuery or Zepto is included on the page, each view has a
  1579. <b>$</b> function that runs queries scoped within the view's element. If you use this
  1580. scoped jQuery function, you don't have to use model ids as part of your query
  1581. to pull out specific elements in a list, and can rely much more on HTML class
  1582. attributes. It's equivalent to running: <tt>$(selector, this.el)</tt>
  1583. </p>
  1584. <pre>
  1585. ui.Chapter = Backbone.View.extend({
  1586. serialize : function() {
  1587. return {
  1588. title: this.$(".title").text(),
  1589. start: this.$(".start-page").text(),
  1590. end: this.$(".end-page").text()
  1591. };
  1592. }
  1593. });
  1594. </pre>
  1595. <p id="View-render">
  1596. <b class="header">render</b><code>view.render()</code>
  1597. <br />
  1598. The default implementation of <b>render</b> is a no-op. Override this
  1599. function with your code that renders the view template from model data,
  1600. and updates <tt>this.el</tt> with the new HTML. A good
  1601. convention is to <tt>return this</tt> at the end of <b>render</b> to
  1602. enable chained calls.
  1603. </p>
  1604. <pre>
  1605. var Bookmark = Backbone.View.extend({
  1606. render: function() {
  1607. $(this.el).html(this.template(this.model.toJSON()));
  1608. return this;
  1609. }
  1610. });
  1611. </pre>
  1612. <p>
  1613. Backbone is agnostic with respect to your preferred method of HTML templating.
  1614. Your <b>render</b> function could even munge together an HTML string, or use
  1615. <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
  1616. choosing a nice JavaScript templating library.
  1617. <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
  1618. <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
  1619. <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
  1620. Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
  1621. <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
  1622. is available, and is an excellent choice if you've already XSS-sanitized
  1623. your interpolated data.
  1624. </p>
  1625. <p>
  1626. Whatever templating strategy you end up with, it's nice if you <i>never</i>
  1627. have to put strings of HTML in your JavaScript. At DocumentCloud, we
  1628. use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
  1629. to package up JavaScript templates stored in <tt>/app/views</tt> as part
  1630. of our main <tt>core.js</tt> asset package.
  1631. </p>
  1632. <p id="View-remove">
  1633. <b class="header">remove</b><code>view.remove()</code>
  1634. <br />
  1635. Convenience function for removing the view from the DOM. Equivalent to calling
  1636. <tt>$(view.el).remove();</tt>
  1637. </p>
  1638. <p id="View-make">
  1639. <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
  1640. <br />
  1641. Convenience function for creating a DOM element of the given type (<b>tagName</b>),
  1642. with optional attributes and HTML content. Used internally to create the
  1643. initial <tt>view.el</tt>.
  1644. </p>
  1645. <pre class="runnable">
  1646. var view = new Backbone.View;
  1647. var el = view.make("b", {className: "bold"}, "Bold! ");
  1648. $("#make-demo").append(el);
  1649. </pre>
  1650. <div id="make-demo"></div>
  1651. <p id="View-delegateEvents">
  1652. <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
  1653. <br />
  1654. Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
  1655. for DOM events within a view.
  1656. If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
  1657. as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
  1658. Omitting the <tt>selector</tt> causes the event to be bound to the view's
  1659. root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
  1660. within the View's constructor for you, so if you have a simple <tt>events</tt>
  1661. hash, all of your DOM events will always already be connected, and you will
  1662. never have to call this function yourself.
  1663. </p>
  1664. <p>
  1665. The <tt>events</tt> property may also be defined as a function that returns
  1666. an <b>events</b> hash, to make it easier to programmatically define your
  1667. events, as well as inherit them from parent views.
  1668. </p>
  1669. <p>
  1670. Using <b>delegateEvents</b> provides a number of advantages over manually
  1671. using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
  1672. callbacks are bound to the view before being handed off to jQuery, so when
  1673. the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
  1674. <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
  1675. hash, all callbacks are removed and delegated afresh &mdash; useful for
  1676. views which need to behave differently when in different modes.
  1677. </p>
  1678. <p>
  1679. A view that displays a document in a search result might look
  1680. something like this:
  1681. </p>
  1682. <pre>
  1683. var DocumentView = Backbone.View.extend({
  1684. events: {
  1685. "dblclick" : "open",
  1686. "click .icon.doc" : "select",
  1687. "contextmenu .icon.doc" : "showMenu",
  1688. "click .show_notes" : "toggleNotes",
  1689. "click .title .lock" : "editAccessLevel",
  1690. "mouseover .title .date" : "showTooltip"
  1691. },
  1692. render: function() {
  1693. $(this.el).html(this.template(this.model.toJSON()));
  1694. return this;
  1695. },
  1696. open: function() {
  1697. window.open(this.model.get("viewer_url"));
  1698. },
  1699. select: function() {
  1700. this.model.set({selected: true});
  1701. },
  1702. ...
  1703. });
  1704. </pre>
  1705. <h2 id="Utility">Utility Functions</h2>
  1706. <p>
  1707. </p>
  1708. <p id="Utility-noConflict">
  1709. <b class="header">noConflict</b><code>var backbone = Backbone.noConflict();</code>
  1710. <br />
  1711. Returns the <tt>Backbone</tt> object back to its original value. You can
  1712. use the return value of <tt>Backbone.noConflict()</tt> to keep a local
  1713. reference to Backbone. Useful for embedding Backbone on third-party
  1714. websites, where you don't want to clobber the existing Backbone.
  1715. </p>
  1716. <pre>
  1717. var localBackbone = Backbone.noConflict();
  1718. var model = localBackbone.Model.extend(...);
  1719. </pre>
  1720. <h2 id="examples">Examples</h2>
  1721. <p id="examples-todos">
  1722. <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
  1723. <a href="examples/todos/index.html">Todo List application</a>
  1724. that is bundled in the repository as Backbone example. If you're wondering
  1725. where to get started with Backbone in general, take a moment to
  1726. <a href="docs/todos.html">read through the annotated source</a>. The app uses a
  1727. <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
  1728. to transparently save all of your todos within your browser, instead of
  1729. sending them to a server. Jérôme also has a version hosted at
  1730. <a href="http://localtodos.com/">localtodos.com</a> that uses a
  1731. <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
  1732. instead of jQuery.
  1733. </p>
  1734. <div style="text-align: center;">
  1735. <a href="examples/todos/index.html">
  1736. <img src="docs/images/todos.png" alt="Todos" class="example_image" />
  1737. </a>
  1738. </div>
  1739. <h2 id="examples-documentcloud">DocumentCloud</h2>
  1740. <p>
  1741. The <a href="http://www.documentcloud.org/public/#search/">DocumentCloud workspace</a>
  1742. is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
  1743. <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
  1744. If you're interested in history &mdash; both Underscore.js and Backbone.js
  1745. were originally extracted from the DocumentCloud codebase, and packaged
  1746. into standalone JS libraries.
  1747. </p>
  1748. <div style="text-align: center;">
  1749. <a href="http://www.documentcloud.org/public/#search/">
  1750. <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" class="example_image" />
  1751. </a>
  1752. </div>
  1753. <h2 id="examples-basecamp">Basecamp Mobile</h2>
  1754. <p>
  1755. <a href="http://37signals.com/">37Signals</a> used Backbone.js to create
  1756. <a href="http://basecamphq.com/mobile">Basecamp Mobile</a>, the mobile version
  1757. of their popular project management software. You can access all your Basecamp
  1758. projects, post new messages, and comment on milestones (all represented
  1759. internally as Backbone.js models).
  1760. </p>
  1761. <div style="text-align: center;">
  1762. <a href="http://basecamphq.com/mobile">
  1763. <img src="docs/images/basecamp-mobile.png" alt="Basecamp Mobile" class="example_image" />
  1764. </a>
  1765. </div>
  1766. <h2 id="examples-flow">Flow</h2>
  1767. <p>
  1768. <a href="http://www.metalabdesign.com/">MetaLab</a> used Backbone.js to create
  1769. <a href="http://www.getflow.com/">Flow</a>, a task management app for teams. The
  1770. workspace relies on Backbone.js to construct task views, activities, accounts,
  1771. folders, projects, and tags. You can see the internals under <tt>window.Flow</tt>.
  1772. </p>
  1773. <div style="text-align: center;">
  1774. <a href="http://www.getflow.com/">
  1775. <img src="docs/images/flow.png" alt="Flow" class="example_image" />
  1776. </a>
  1777. </div>
  1778. <h2 id="examples-groupon">Groupon Now!</h2>
  1779. <p>
  1780. <a href="http://www.groupon.com/now">Groupon Now!</a> helps you find
  1781. local deals that you can buy and use right now. When first developing
  1782. the product, the team decided it would be AJAX heavy with smooth transitions
  1783. between sections instead of full refreshes, but still needed to be fully
  1784. linkable and shareable. Despite never having used Backbone before, the
  1785. learning curve was incredibly quick &mdash; a prototype was hacked out in an
  1786. afternoon, and the team was able to ship the product in two weeks.
  1787. Because the source is minimal and understandable, it was easy to
  1788. add several Backbone extensions for Groupon Now!: changing the router
  1789. to handle URLs with querystring parameters, and adding a simple
  1790. in-memory store for caching repeated requests for the same data.
  1791. </p>
  1792. <div style="text-align: center;">
  1793. <a href="http://www.groupon.com/now">
  1794. <img src="docs/images/groupon.png" alt="Groupon Now!" class="example_image" />
  1795. </a>
  1796. </div>
  1797. <h2 id="examples-trajectory">Trajectory</h2>
  1798. <p>
  1799. <a href="https://www.apptrajectory.com/">Trajectory</a> is an agile
  1800. software planning tool used to discuss wireframes, record decisions made,
  1801. relate user stories and bugs to discussions, and track your progress and
  1802. plan the future. With Rails on the backend, Trajectory uses Backbone.js
  1803. heavily to provide a fluid story planning interface that even updates in
  1804. real-time based on the actions of other users.
  1805. </p>
  1806. <div style="text-align: center;">
  1807. <a href="http://www.apptrajectory.com/">
  1808. <img src="docs/images/trajectory.png" alt="Trajectory" class="example_image" />
  1809. </a>
  1810. </div>
  1811. <h2 id="examples-soundcloud">SoundCloud Mobile</h2>
  1812. <p>
  1813. <a href="http://soundcloud.com">SoundCloud</a> is the leading sound sharing
  1814. platform on the internet, and Backbone.js provides the foundation for
  1815. <a href="http://m.soundcloud.com">SoundCloud Mobile</a>. The project uses
  1816. the public SoundCloud <a href="http://soundcloud.com/developers">API</a>
  1817. as a data source (channeled through a nginx proxy),
  1818. <a href="http://api.jquery.com/category/plugins/templates/">jQuery templates</a>
  1819. for the rendering, <a href="http://docs.jquery.com/Qunit">Qunit
  1820. </a> and <a href="http://code.google.com/p/phantomjs/">PhantomJS</a> for
  1821. the testing suite. The JS code, templates and CSS are built for the
  1822. production deployment with various Node.js tools like
  1823. <a href="https://github.com/dsimard/ready.js">ready.js</a>,
  1824. <a href="https://github.com/mde/node-jake">Jake</a>,
  1825. <a href="https://github.com/tmpvar/jsdom">jsdom</a>.
  1826. The <b>Backbone.History</b> was modified to support the HTML5 <tt>history.pushState</tt>.
  1827. <b>Backbone.sync</b> was extended with an additional SessionStorage based cache
  1828. layer.
  1829. </p>
  1830. <div style="text-align: center;">
  1831. <a href="http://m.soundcloud.com">
  1832. <img src="docs/images/soundcloud.png" alt="SoundCloud" class="example_image" />
  1833. </a>
  1834. </div>
  1835. <h2 id="examples-pandora">Pandora</h2>
  1836. <p>
  1837. When <a href="http://www.pandora.com/newpandora">Pandora</a> redesigned
  1838. their site in HTML5, they chose Backbone.js to help
  1839. manage the user interface and interactions. For example, there's a model
  1840. that represents the "currently playing track", and multiple views that
  1841. automatically update when the current track changes. The station list is a
  1842. collection, so that when stations are added or changed, the UI stays up to date.
  1843. </p>
  1844. <div style="text-align: center;">
  1845. <a href="http://www.pandora.com/newpandora">
  1846. <img src="docs/images/pandora.png" alt="Pandora" class="example_image" />
  1847. </a>
  1848. </div>
  1849. <h2 id="examples-cloudapp">CloudApp</h2>
  1850. <p>
  1851. <a href="http://getcloudapp.com">CloudApp</a> is simple file and link
  1852. sharing for the Mac. Backbone.js powers the web tools
  1853. which consume the <a href="http://developer.getcloudapp.com">documented API</a>
  1854. to manage Drops. Data is either pulled manually or pushed by
  1855. <a href="http://pusher.com">Pusher</a> and fed to
  1856. <a href="http://github.com/janl/mustache.js">Mustache</a> templates for
  1857. rendering. Check out the <a href="http://cloudapp.github.com/engine">annotated source code</a>
  1858. to see the magic.
  1859. </p>
  1860. <div style="text-align: center;">
  1861. <a href="http://getcloudapp.com">
  1862. <img src="docs/images/cloudapp.png" alt="CloudApp" class="example_image" />
  1863. </a>
  1864. </div>
  1865. <h2 id="examples-seatgeek">SeatGeek</h2>
  1866. <p>
  1867. <a href="http://seatgeek.com">SeatGeek</a>'s stadium ticket maps were originally
  1868. developed with Prototype.js. Moving to Backbone.js and jQuery helped organize
  1869. a lot of the UI code, and the increased structure has made adding features
  1870. a lot easier. SeatGeek is also in the process of building a mobile
  1871. interface that will be Backbone.js from top to bottom.
  1872. </p>
  1873. <div style="text-align: center;">
  1874. <a href="http://seatgeek.com">
  1875. <img src="docs/images/seatgeek.png" alt="SeatGeek" class="example_image" />
  1876. </a>
  1877. </div>
  1878. <h2 id="examples-tpm">Talking Points Memo: Baroque</h2>
  1879. <p>
  1880. <a href="http://labs.talkingpointsmemo.com/2011/08/the-baroque-era.php">Baroque</a>
  1881. is the editor currently powering the homepage of
  1882. <a href="http://talkingpointsmemo.com/">Talking Points Memo</a>.
  1883. With a Sinatra backend for publishing, Baroque uses Backbone.js to provide
  1884. real-time story and asset dropping, complex reordering actions and copy
  1885. editing, making web layout feel much more like print layout.
  1886. </p>
  1887. <div style="text-align: center;">
  1888. <a href="http://labs.talkingpointsmemo.com/2011/08/the-baroque-era.php">
  1889. <img src="docs/images/baroque.jpg" alt="Baroque" class="example_image" />
  1890. </a>
  1891. </div>
  1892. <h2 id="examples-hotel-tonight">Hotel Tonight</h2>
  1893. <p>
  1894. <a href="http://www.hoteltonight.com/">Hotel Tonight</a> used Backbone.js,
  1895. <a href="http://coffeescript.org">CoffeeScript</a>,
  1896. <a href="http://documentcloud.github.com/jammit/">Jammit</a> and more to
  1897. create the
  1898. <a href="https://market.android.com/details?id=com.hoteltonight.android.prod">Android version</a>
  1899. of their app; a last-minute, mobile, hotel booking application. The app
  1900. leverages Backbone for the bulk of its architecture, with jQuery Mobile
  1901. coming in for visual presentation.
  1902. </p>
  1903. <div style="text-align: center;">
  1904. <a href="http://www.hoteltonight.com">
  1905. <img src="docs/images/hotel-tonight.png" alt="Hotel Tonight" class="example_image" />
  1906. </a>
  1907. </div>
  1908. <h2 id="examples-quoteroller">Quote Roller</h2>
  1909. <p>
  1910. <a href="http://www.codingstaff.com">Coding Staff</a> used Backbone.js to
  1911. create <a href="http://www.quoteroller.com">Quote Roller</a>, an application
  1912. that helps to create, send, organize and track business proposals with ease.
  1913. Backbone.js has been used to implement interactive parts of the
  1914. application like template builder, pricing table, file attachments manager.
  1915. </p>
  1916. <div style="text-align: center;">
  1917. <a href="http://www.quoteroller.com">
  1918. <img src="docs/images/quoteroller.png" alt="Quote Roller" class="example_image" />
  1919. </a>
  1920. </div>
  1921. <h2 id="examples-tilemill">TileMill</h2>
  1922. <p>
  1923. Our fellow
  1924. <a href="http://www.newschallenge.org/">Knight Foundation News Challenge</a>
  1925. winners, <a href="http://mapbox.com/">MapBox</a>, created an open-source
  1926. map design studio with Backbone.js:
  1927. <a href="http://mapbox.github.com/tilemill/">TileMill</a>.
  1928. TileMill lets you manage map layers based on shapefiles and rasters, and
  1929. edit their appearance directly in the browser with the
  1930. <a href="https://github.com/mapbox/carto">Carto styling language</a>.
  1931. Note that the gorgeous <a href="http://mapbox.com/">MapBox</a> homepage
  1932. is also a Backbone.js app.
  1933. </p>
  1934. <div style="text-align: center;">
  1935. <a href="http://mapbox.github.com/tilemill/">
  1936. <img src="docs/images/tilemill.png" alt="TileMill" class="example_image" />
  1937. </a>
  1938. </div>
  1939. <h2 id="examples-menagerievet">Menagerie Whiteboard</h2>
  1940. <p>
  1941. <a href="http://twitter.com/_aaron_">Aaron Hamid</a> and
  1942. <a href="http://twitter.com/mkuklis">Michal Kuklis</a> from
  1943. <a href="http://incandescentsoftware.com">Incandescent Software</a>
  1944. used Backbone.js to create
  1945. <a href="http://menagerievet.com">Menagerie Whiteboard</a> a digital
  1946. "whiteboard" for veterinary practices. Backbone <b>Models</b> were used to
  1947. sync the data with CouchDB. A Backbone <b>Controller</b> was used for
  1948. routing and bookmarkable deep links. Backbone <b>Views</b> were used to
  1949. bind, listen and 'react' to changes coming from models.
  1950. <b>Backbone.sync</b> was extended to support connection to CouchDB
  1951. and deployment as a CouchApp.
  1952. </p>
  1953. <div style="text-align: center;">
  1954. <a href="http://menagerievet.com/">
  1955. <img src="docs/images/menagerievet.png" alt="MenagerieVet" class="example_image" />
  1956. </a>
  1957. </div>
  1958. <h2 id="examples-blossom">Blossom</h2>
  1959. <p>
  1960. <a href="http://blossom.io">Blossom</a> is a lightweight project management
  1961. tool for lean teams. Backbone.js is heavily used in combination with
  1962. <a href="http://coffeescript.org">CoffeeScript</a> to provide a smooth
  1963. interaction experience. The RESTful backend is built
  1964. with <a href="http://flask.pocoo.org/">Flask</a> on Google App Engine.
  1965. </p>
  1966. <div style="text-align: center;">
  1967. <a href="http://blossom.io">
  1968. <img src="docs/images/blossom.png" alt="Blossom" class="example_image" />
  1969. </a>
  1970. </div>
  1971. <h2 id="examples-instagreat">Insta-great!</h2>
  1972. <p>
  1973. <a href="http://twitter.com/elliottkember">Elliott Kember</a> and
  1974. <a href="http://twitter.com/dizzyup">Hector Simpson</a> built
  1975. <a href="http://instagre.at">Insta-great!</a>
  1976. - a fun way to explore popular photos and interact with
  1977. <a href="http://instagram.com/">Instagram</a> on the web.
  1978. Elliott says, "Backbone.js and Coffeescript were insanely useful for
  1979. writing clean, consistent UI code and keeping everything modular and
  1980. readable, even through several code refactors. I'm in love."
  1981. </p>
  1982. <div style="text-align: center;">
  1983. <a href="http://instagre.at">
  1984. <img src="docs/images/instagreat.png" alt="instagre.at" class="example_image" />
  1985. </a>
  1986. </div>
  1987. <h2 id="examples-decide">Decide</h2>
  1988. <p>
  1989. <a href="http://decide.com">Decide.com</a> helps people decide when to buy
  1990. consumer electronics. It relies heavily on Backbone.js to render and
  1991. update its Search Results Page. An "infinite scroll" feature takes
  1992. advantage of a SearchResults model containing a collection of
  1993. Product models to fetch more results and render them on the fly
  1994. with Mustache. A SearchController keeps everything in sync and
  1995. maintains page state in the URL. Backbone also powers the user
  1996. accounts and settings management.
  1997. </p>
  1998. <div style="text-align: center;">
  1999. <a href="http://decide.com">
  2000. <img src="docs/images/decide.png" alt="Decide" class="example_image" />
  2001. </a>
  2002. </div>
  2003. <h2 id="examples-bittorrent">BitTorrent</h2>
  2004. <p>
  2005. <a href="http://www.bittorrent.com">BitTorrent</a> used Backbone to
  2006. completely rework an existing Win32 UI. Models normalize access to the
  2007. client's data and views rely heavily on the <tt>change</tt> events to keep
  2008. the UI state current. Using Backbone and SCSS,
  2009. <a href="http://www.bittorrent.com/chrysalis/">our new design</a> and UX
  2010. prototypes are considerably easier to iterate, test and work with than
  2011. the original Win32 UI.
  2012. </p>
  2013. <div style="text-align: center;">
  2014. <a href="http://www.bittorrent.com/chrysalis/">
  2015. <img src="docs/images/bittorrent.jpg" alt="BitTorrent" class="example_image" />
  2016. </a>
  2017. </div>
  2018. <h2 id="examples-trapit">Trapit</h2>
  2019. <p>
  2020. <a href="http://trap.it">Trapit</a> brings the web to you, scouring
  2021. the web on your behalf, 24/7. The product, currently in private beta,
  2022. uses Backbone to organize the best, most relevant content into individual
  2023. "traps" on your favorite topics and interests.
  2024. </p>
  2025. <div style="text-align: center;">
  2026. <a href="http://trap.it">
  2027. <img src="docs/images/trapit.png" alt="Trapit" class="example_image" />
  2028. </a>
  2029. </div>
  2030. <h2 id="examples-fluxiom">Fluxiom</h2>
  2031. <p>
  2032. <a href="http://fluxiom.com">Fluxiom</a> uses Backbone.js and HTML5 to
  2033. deliver a seamless upload experience from the desktop to the cloud,
  2034. including drag and drop, live previews, partial uploads, and one-click sharing.
  2035. <p>
  2036. <p>
  2037. The upload queue is a single collection and each file is its own model.
  2038. The UI is divided into several views for efficient event handling, and
  2039. uses <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
  2040. templates for fast rendering, even when handling hundreds of uploads.
  2041. </p>
  2042. <div style="text-align: center;">
  2043. <a href="http://fluxiom.com/">
  2044. <img src="docs/images/fluxiom.png" alt="Fluxiom" class="example_image" />
  2045. </a>
  2046. </div>
  2047. <h2 id="examples-chop">Chop</h2>
  2048. <p>
  2049. <a href="http://chopapp.com/">Chop</a> is a little app from
  2050. <a href="http://www.zurb.com/">ZURB</a> that lets people slice up bad code
  2051. and share their feedback to help put it back together.
  2052. Chop was built to demonstrate how easy it is to build pageless apps
  2053. using Backbone.js and Rails. Chop makes extensive use of Backbone <b>Views</b>,
  2054. <b>Controllers</b>, and <b>Models</b>.
  2055. </p>
  2056. <div style="text-align: center;">
  2057. <a href="http://chopapp.com/">
  2058. <img src="docs/images/chop.png" alt="Chop" class="example_image" />
  2059. </a>
  2060. </div>
  2061. <h2 id="examples-test-kitchen">America&rsquo;s Test Kitchen</h2>
  2062. <p>
  2063. <a href="http://www.testkitchenschool.com/">America&rsquo;s Test Kitchen</a>,
  2064. an online cooking school, uses Backbone.js to manage quizzes, polls,
  2065. kitchen assignments, recipe tutorials and a hybrid HTML5/Flash video player.
  2066. The whole Backbone codebase is about 5k SLOC, with Mustache.js for
  2067. templating, and Rails on the back end. <a href="http://wir35.com/">Max Lord</a>
  2068. writes: &ldquo;Working with Backbone made this one of the most pleasurable
  2069. large scale client-side projects I have ever worked on, and I am definitely
  2070. planning on continuing to work with it.&rdquo;
  2071. </p>
  2072. <div style="text-align: center;">
  2073. <a href="http://www.testkitchenschool.com/">
  2074. <img src="docs/images/test-kitchen.png" alt="America's Test Kitchen" class="example_image" />
  2075. </a>
  2076. </div>
  2077. <h2 id="examples-quietwrite">QuietWrite</h2>
  2078. <p>
  2079. <a href="http://www.twitter.com/jamesjyu">James Yu</a> used Backbone.js to
  2080. create <a href="http://www.quietwrite.com/">QuietWrite</a>, an app
  2081. that gives writers a clean and quiet interface to concentrate on the text itself.
  2082. The editor relies on Backbone to persist document data to the server. He
  2083. followed up with a Backbone.js + Rails tutorial that describes how to implement
  2084. <a href="http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/">CloudEdit, a simple document editing app</a>.
  2085. </p>
  2086. <div style="text-align: center;">
  2087. <a href="http://www.quietwrite.com/">
  2088. <img src="docs/images/quietwrite.png" alt="QuietWrite" class="example_image" />
  2089. </a>
  2090. </div>
  2091. <h2 id="examples-tzigla">Tzigla</h2>
  2092. <p>
  2093. <a href="http://twitter.com/evilchelu">Cristi Balan</a> and
  2094. <a href="http://dira.ro">Irina Dumitrascu</a> created
  2095. <a href="http://tzigla.com">Tzigla</a>, a collaborative drawing
  2096. application where artists make tiles that connect to each other to
  2097. create <a href="http://tzigla.com/boards/1">surreal drawings</a>.
  2098. Backbone models help organize the code, routers provide
  2099. <a href="http://tzigla.com/boards/1#!/tiles/2-2">bookmarkable deep links</a>,
  2100. and the views are rendered with
  2101. <a href="https://github.com/creationix/haml-js">haml.js</a> and
  2102. <a href="http://zeptojs.com/">Zepto</a>.
  2103. Tzigla is written in Ruby (Rails) on the backend, and
  2104. <a href="http://coffeescript.org">CoffeeScript</a> on the frontend, with
  2105. <a href="http://documentcloud.github.com/jammit/">Jammit</a>
  2106. prepackaging the static assets.
  2107. </p>
  2108. <div style="text-align: center;">
  2109. <a href="http://www.tzigla.com/">
  2110. <img src="docs/images/tzigla.png" alt="Tzigla" class="example_image" />
  2111. </a>
  2112. </div>
  2113. <h2 id="examples-substance">Substance</h2>
  2114. <p>
  2115. Michael Aufreiter is building an open source document authoring and
  2116. publishing engine: <a href="http://substance.io">Substance</a>.
  2117. Substance makes use of Backbone.View and Backbone.Router, while
  2118. Backbone plays well together with
  2119. <a href="http://github.com/michael/data">Data.js</a>, which is used for
  2120. data persistence.
  2121. </p>
  2122. <div style="text-align: center;">
  2123. <a href="http://substance.io/">
  2124. <img src="docs/images/substance.png" alt="Substance" class="example_image" />
  2125. </a>
  2126. </div>
  2127. <h2 id="faq">F.A.Q.</h2>
  2128. <p id="FAQ-events">
  2129. <b class="header">Catalog of Events</b>
  2130. <br />
  2131. Here's a list of all of the built-in events that Backbone.js can fire.
  2132. You're also free to trigger your own events on Models and Views as you
  2133. see fit.
  2134. </p>
  2135. <ul>
  2136. <li><b>"add"</b> (model, collection) &mdash; when a model is added to a collection. </li>
  2137. <li><b>"remove"</b> (model, collection) &mdash; when a model is removed from a collection. </li>
  2138. <li><b>"reset"</b> (collection) &mdash; when the collection's entire contents have been replaced. </li>
  2139. <li><b>"change"</b> (model, collection) &mdash; when a model's attributes have changed. </li>
  2140. <li><b>"change:[attribute]"</b> (model, collection) &mdash; when a specific attribute has been updated. </li>
  2141. <li><b>"destroy"</b> (model, collection) &mdash; when a model is <a href="#Model-destroy">destroyed</a>. </li>
  2142. <li><b>"error"</b> (model, collection) &mdash; when a model's validation fails, or a <a href="#Model-save">save</a> call fails on the server. </li>
  2143. <li><b>"route:[name]"</b> (router) &mdash; when one of a router's routes has matched. </li>
  2144. <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
  2145. </ul>
  2146. <p id="FAQ-tim-toady">
  2147. <b class="header">There's More Than One Way To Do It</b>
  2148. <br />
  2149. It's common for folks just getting started to treat the examples listed
  2150. on this page as some sort of gospel truth. In fact, Backbone.js is intended
  2151. to be fairly agnostic about many common patterns in client-side code.
  2152. For example...
  2153. </p>
  2154. <p>
  2155. <b>References between Models and Views</b> can be handled several ways.
  2156. Some people like to have direct pointers, where views correspond 1:1 with
  2157. models (<tt>model.view</tt> and <tt>view.model</tt>). Others prefer to have intermediate
  2158. "controller" objects that orchestrate the creation and organization of
  2159. views into a hierarchy. Others still prefer the evented approach, and always
  2160. fire events instead of calling methods directly. All of these styles work well.
  2161. </p>
  2162. <p>
  2163. <b>Batch operations</b> on Models are common, but often best handled differently
  2164. depending on your server-side setup. Some folks don't mind making individual
  2165. Ajax requests. Others create explicit resources for RESTful batch operations:
  2166. <tt>/notes/batch/destroy?ids=1,2,3,4</tt>. Others tunnel REST over JSON, with the
  2167. creation of "changeset" requests:
  2168. </p>
  2169. <pre>
  2170. {
  2171. "create": [array of models to create]
  2172. "update": [array of models to update]
  2173. "destroy": [array of model ids to destroy]
  2174. }
  2175. </pre>
  2176. <p>
  2177. <b>Feel free to define your own events.</b> <a href="#Events">Backbone.Events</a>
  2178. is designed so that you can mix it in to any JavaScript object or prototype.
  2179. Since you can use any string as an event, it's often handy to bind
  2180. and trigger your own custom events: <tt>model.bind("selected:true")</tt> or
  2181. <tt>model.bind("editing")</tt>
  2182. </p>
  2183. <p>
  2184. <b>Render the UI</b> as you see fit. Backbone is agnostic as to whether you
  2185. use <a href="http://documentcloud.github.com/underscore/#template">Underscore templates</a>,
  2186. <a href="https://github.com/janl/mustache.js">Mustache.js</a>, direct DOM
  2187. manipulation, server-side rendered snippets of HTML, or
  2188. <a href="http://jqueryui.com/">jQuery UI</a> in your <tt>render</tt> function.
  2189. Sometimes you'll create a view for each model ... sometimes you'll have a
  2190. view that renders thousands of models at once, in a tight loop. Both can be
  2191. appropriate in the same app, depending on the quantity of data involved,
  2192. and the complexity of the UI.
  2193. </p>
  2194. <p id="FAQ-nested">
  2195. <b class="header">Nested Models &amp; Collections</b>
  2196. <br />
  2197. It's common to nest collections inside of models with Backbone. For example,
  2198. consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
  2199. One nice pattern for handling this is have a <tt>this.messages</tt> collection
  2200. for each mailbox, enabling the lazy-loading of messages, when the mailbox
  2201. is first opened ... perhaps with <tt>MessageList</tt> views listening for
  2202. <tt>"add"</tt> and <tt>"remove"</tt> events.
  2203. </p>
  2204. <pre>
  2205. var Mailbox = Backbone.Model.extend({
  2206. initialize: function() {
  2207. this.messages = new Messages;
  2208. this.messages.url = '/mailbox/' + this.id + '/messages';
  2209. this.messages.bind("reset", this.updateCounts);
  2210. },
  2211. ...
  2212. });
  2213. var Inbox = new Mailbox;
  2214. // And then, when the Inbox is opened:
  2215. Inbox.messages.fetch();
  2216. </pre>
  2217. <p>
  2218. If you're looking for something more opinionated, there are a number of
  2219. Backbone plugins that add sophisticated associations among models,
  2220. <a href="https://github.com/documentcloud/backbone/wiki/Extensions%2C-Plugins%2C-Resources">available on the wiki</a>.
  2221. </p>
  2222. <p id="FAQ-bootstrap">
  2223. <b class="header">Loading Bootstrapped Models</b>
  2224. <br />
  2225. When your app first loads, it's common to have a set of initial models that
  2226. you know you're going to need, in order to render the page. Instead of
  2227. firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
  2228. a nicer pattern is to have their data already bootstrapped into the page.
  2229. You can then use <a href="#Collection-reset">reset</a> to populate your
  2230. collections with the initial data. At DocumentCloud, in the
  2231. <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
  2232. workspace, we do something along these lines:
  2233. </p>
  2234. <pre>
  2235. &lt;script&gt;
  2236. Accounts.reset(&lt;%= @accounts.to_json %&gt;);
  2237. Projects.reset(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
  2238. &lt;/script&gt;
  2239. </pre>
  2240. <p id="FAQ-mvc">
  2241. <b class="header">How does Backbone relate to "traditional" MVC?</b>
  2242. <br />
  2243. Different implementations of the
  2244. <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
  2245. pattern tend to disagree about the definition of a controller. If it helps any, in
  2246. Backbone, the <a href="#View">View</a> class can also be thought of as a
  2247. kind of controller, dispatching events that originate from the UI, with
  2248. the HTML template serving as the true view. We call it a View because it
  2249. represents a logical chunk of UI, responsible for the contents of a single
  2250. DOM element.
  2251. </p>
  2252. <p>
  2253. Comparing the overall structure of Backbone to a server-side MVC framework
  2254. like <b>Rails</b>, the pieces line up like so:
  2255. </p>
  2256. <ul>
  2257. <li>
  2258. <b>Backbone.Model</b> &ndash; Like a Rails model minus the class
  2259. methods. Wraps a row of data in business logic.
  2260. </li>
  2261. <li>
  2262. <b>Backbone.Collection</b> &ndash; A group of models on the client-side,
  2263. with sorting/filtering/aggregation logic.
  2264. </li>
  2265. <li>
  2266. <b>Backbone.Router</b> &ndash; Rails <tt>routes.rb</tt> + Rails controller
  2267. actions. Maps URLs to functions.
  2268. </li>
  2269. <li>
  2270. <b>Backbone.View</b> &ndash; A logical, re-usable piece of UI. Often,
  2271. but not always, associated with a model.
  2272. </li>
  2273. <li>
  2274. <b>Client-side Templates</b> &ndash; Rails <tt>.html.erb</tt> views,
  2275. rendering a chunk of HTML.
  2276. </li>
  2277. </ul>
  2278. <p id="FAQ-this">
  2279. <b class="header">Binding "this"</b>
  2280. <br />
  2281. Perhaps the single most common JavaScript "gotcha" is the fact that when
  2282. you pass a function as a callback, its value for <tt>this</tt> is lost. With
  2283. Backbone, when dealing with <a href="#Events">events</a> and callbacks,
  2284. you'll often find it useful to rely on
  2285. <a href="http://documentcloud.github.com/underscore/#bind">_.bind</a> and
  2286. <a href="http://documentcloud.github.com/underscore/#bindAll">_.bindAll</a>
  2287. from Underscore.js.
  2288. </p>
  2289. <p>
  2290. When binding callbacks to Backbone events, you can choose to pass an optional
  2291. third argument to specify the <tt>this</tt> that will be used when the
  2292. callback is later invoked:
  2293. </p>
  2294. <pre>
  2295. var MessageList = Backbone.View.extend({
  2296. initialize: function() {
  2297. var messages = this.collection;
  2298. messages.bind("reset", this.render, this);
  2299. messages.bind("add", this.addMessage, this);
  2300. messages.bind("remove", this.removeMessage, this);
  2301. }
  2302. });
  2303. // Later, in the app...
  2304. Inbox.messages.add(newMessage);
  2305. </pre>
  2306. <h2 id="changelog">Change Log</h2>
  2307. <p>
  2308. <b class="header">0.5.3</b> &mdash; <small><i>August 9, 2011</i></small><br />
  2309. A View's <tt>events</tt> property may now be defined as a function, as well
  2310. as an object literal, making it easier to programmatically define and inherit
  2311. events. <tt>groupBy</tt> is now proxied from Underscore as a method on Collections.
  2312. If the server has already rendered everything on page load, pass
  2313. <tt>Backbone.history.start({silent: true})</tt> to prevent the initial route
  2314. from triggering. Bugfix for pushState with encoded URLs.
  2315. </p>
  2316. <p>
  2317. <b class="header">0.5.2</b> &mdash; <small><i>July 26, 2011</i></small><br />
  2318. The <tt>bind</tt> function, can now take an optional third argument, to specify
  2319. the <tt>this</tt> of the callback function.
  2320. Multiple models with the same <tt>id</tt> are now allowed in a collection.
  2321. Fixed a bug where calling <tt>.fetch(jQueryOptions)</tt> could cause an
  2322. incorrect URL to be serialized.
  2323. Fixed a brief extra route fire before redirect, when degrading from
  2324. <tt>pushState</tt>.
  2325. </p>
  2326. <p>
  2327. <b class="header">0.5.1</b> &mdash; <small><i>July 5, 2011</i></small><br />
  2328. Cleanups from the 0.5.0 release, to wit: improved transparent upgrades from
  2329. hash-based URLs to pushState, and vice-versa. Fixed inconsistency with
  2330. non-modified attributes being passed to <tt>Model#initialize</tt>. Reverted
  2331. a <b>0.5.0</b> change that would strip leading hashbangs from routes.
  2332. Added <tt>contains</tt> as an alias for <tt>includes</tt>.
  2333. </p>
  2334. <p>
  2335. <b class="header">0.5.0</b> &mdash; <small><i>July 1, 2011</i></small><br />
  2336. A large number of tiny tweaks and micro bugfixes, best viewed by looking
  2337. at <a href="https://github.com/documentcloud/backbone/compare/0.3.3...0.5.0">the commit diff</a>.
  2338. HTML5 <tt>pushState</tt> support, enabled by opting-in with:
  2339. <tt>Backbone.history.start({pushState: true})</tt>.
  2340. <tt>Controller</tt> was renamed to <tt>Router</tt>, for clarity.
  2341. <tt>Collection#refresh</tt> was renamed to <tt>Collection#reset</tt> to emphasize
  2342. its ability to both reset the collection with new models, as well as empty
  2343. out the collection when used with no parameters.
  2344. <tt>saveLocation</tt> was replaced with <tt>navigate</tt>.
  2345. RESTful persistence methods (save, fetch, etc.) now return the jQuery deferred
  2346. object for further success/error chaining and general convenience.
  2347. Improved XSS escaping for <tt>Model#escape</tt>.
  2348. Added a <tt>urlRoot</tt> option to allow specifying RESTful urls without
  2349. the use of a collection.
  2350. An error is thrown if <tt>Backbone.history.start</tt> is called multiple times.
  2351. <tt>Collection#create</tt> now validates before initializing the new model.
  2352. <tt>view.el</tt> can now be a jQuery string lookup.
  2353. Backbone Views can now also take an <tt>attributes</tt> parameter.
  2354. <tt>Model#defaults</tt> can now be a function as well as a literal attributes
  2355. object.
  2356. </p>
  2357. <p>
  2358. <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
  2359. Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
  2360. jQuery, as a framework for DOM manipulation and Ajax support.
  2361. Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
  2362. attributes intended for HTML interpolation. When trying to persist a model,
  2363. failed requests will now trigger an <tt>"error"</tt> event. The
  2364. ubiquitous <tt>options</tt> argument is now passed as the final argument
  2365. to all <tt>"change"</tt> events.
  2366. </p>
  2367. <p>
  2368. <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
  2369. Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
  2370. overridden on a per-model, or per-collection basis. Fixed recursion error
  2371. when calling <tt>save</tt> with no changed attributes, within a
  2372. <tt>"change"</tt> event.
  2373. </p>
  2374. <p>
  2375. <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
  2376. All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
  2377. model, so that views can listen for them without having to know about the
  2378. collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
  2379. <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
  2380. Backbone routes are now able to load empty URL fragments.
  2381. </p>
  2382. <p>
  2383. <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
  2384. Backbone now has <a href="#Controller">Controllers</a> and
  2385. <a href="#History">History</a>, for doing client-side routing based on
  2386. URL fragments.
  2387. Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
  2388. do <tt>PUT</tt> and <tt>DELETE</tt>.
  2389. Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
  2390. encoded requests.
  2391. Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
  2392. from a model.
  2393. All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
  2394. </p>
  2395. <p>
  2396. <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
  2397. Instead of requiring server responses to be namespaced under a <tt>model</tt>
  2398. key, now you can define your own <a href="#Model-parse">parse</a> method
  2399. to convert responses into attributes for Models and Collections.
  2400. The old <tt>handleEvents</tt> function is now named
  2401. <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
  2402. called as part of the View's constructor.
  2403. Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
  2404. Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
  2405. </p>
  2406. <p>
  2407. <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
  2408. Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
  2409. attributes of single model from the server.
  2410. An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
  2411. as an option, which will be invoked if validation fails, overriding the
  2412. <tt>"error"</tt> event.
  2413. You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
  2414. methods by setting <tt>Backbone.emulateHTTP = true</tt>.
  2415. Existing Model and Collection data is no longer sent up unnecessarily with
  2416. <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
  2417. Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
  2418. </p>
  2419. <p>
  2420. <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
  2421. Added a convention for <tt>initialize</tt> functions to be called
  2422. upon instance construction, if defined. Documentation tweaks.
  2423. </p>
  2424. <p>
  2425. <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
  2426. Initial Backbone release.
  2427. </p>
  2428. <p>
  2429. <br />
  2430. <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
  2431. <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
  2432. </a>
  2433. </p>
  2434. </div>
  2435. <script src="test/vendor/underscore-1.1.6.js"></script>
  2436. <script src="test/vendor/jquery-1.5.js"></script>
  2437. <script src="test/vendor/json2.js"></script>
  2438. <script src="backbone.js"></script>
  2439. <script>
  2440. // Set up the "play" buttons for each runnable code example.
  2441. $(function() {
  2442. $('.runnable').each(function() {
  2443. var code = this;
  2444. var button = $('<div class="run" title="Run"></div>');
  2445. $(button).insertBefore(code).bind('click', function(){
  2446. eval($(code).text());
  2447. });
  2448. });
  2449. });
  2450. </script>
  2451. </body>
  2452. </html>