PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/index.html

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