PageRenderTime 80ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

https://github.com/webspinner/backbone
HTML | 2343 lines | 2013 code | 330 blank | 0 comment | 0 complexity | 866c1dd738eb15b5be4379d5b9f7b82a 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 30px;
  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.3.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 (25)</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-refresh">refresh</a></li>
  218. <li> <a href="#Collection-create">create</a></li>
  219. </ul>
  220. <a class="toc_title" href="#Controller">
  221. Controller
  222. </a>
  223. <ul class="toc_section">
  224. <li> <a href="#Controller-extend">extend</a></li>
  225. <li> <a href="#Controller-routes">routes</a></li>
  226. <li> <a href="#Controller-constructor">constructor / initialize</a></li>
  227. <li> <a href="#Controller-route">route</a></li>
  228. <li> <a href="#Controller-saveLocation">saveLocation</a></li>
  229. </ul>
  230. <a class="toc_title" href="#History">
  231. History
  232. </a>
  233. <ul class="toc_section">
  234. <li> <a href="#History-start">start</a></li>
  235. </ul>
  236. <a class="toc_title" href="#Sync">
  237. Sync
  238. </a>
  239. <ul class="toc_section">
  240. <li> <a href="#Sync">Backbone.sync</a></li>
  241. <li> <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
  242. <li> <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
  243. </ul>
  244. <a class="toc_title" href="#View">
  245. View
  246. </a>
  247. <ul class="toc_section">
  248. <li> <a href="#View-extend">extend</a></li>
  249. <li> <a href="#View-constructor">constructor / initialize</a></li>
  250. <li> <a href="#View-el">el</a></li>
  251. <li> <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
  252. <li> <a href="#View-render">render</a></li>
  253. <li> <a href="#View-remove">remove</a></li>
  254. <li> <a href="#View-make">make</a></li>
  255. <li> <a href="#View-delegateEvents">delegateEvents</a></li>
  256. </ul>
  257. <a class="toc_title" href="#Utility">
  258. Utility
  259. </a>
  260. <ul class="toc_section">
  261. <li> <a href="#Utility-noConflict">noConflict</a></li>
  262. </ul>
  263. <a class="toc_title" href="#examples">
  264. Examples
  265. </a>
  266. <ul class="toc_section">
  267. <li> <a href="#examples-todos">Todos</a></li>
  268. <li> <a href="#examples-documentcloud">DocumentCloud</a></li>
  269. <li> <a href="#examples-basecamp">Basecamp Mobile</a></li>
  270. <li> <a href="#examples-flow">Flow</a></li>
  271. <li> <a href="#examples-tilemill">TileMill</a></li>
  272. <li> <a href="#examples-soundcloud">Mobile SoundCloud</a></li>
  273. <li>- <a href="#examples-instagreat">Insta-great!</a></li>
  274. <li>- <a href="#examples-quietwrite">QuietWrite</a></li>
  275. <li>- <a href="#examples-tzigla">Tzigla</a></li>
  276. <li>- <a href="#examples-substance">Substance</a></li>
  277. </ul>
  278. <a class="toc_title" href="#faq">
  279. F.A.Q.
  280. </a>
  281. <ul class="toc_section">
  282. <li> <a href="#FAQ-events">Catalog of Events</a></li>
  283. <li> <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
  284. <li> <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
  285. <li> <a href="#FAQ-mvc">Traditional MVC</a></li>
  286. <li> <a href="#FAQ-this">Binding "this"</a></li>
  287. <li>- <a href="#FAQ-rias">Other RIA Frameworks</a></li>
  288. </ul>
  289. <a class="toc_title" href="#changelog">
  290. Change Log
  291. </a>
  292. </div>
  293. <div class="container">
  294. <p>
  295. <img style="width: 385px; height: 126px;" src="docs/images/backbone.png" alt="Backbone.js" />
  296. </p>
  297. <p>
  298. <a href="http://github.com/documentcloud/backbone/">Backbone</a>
  299. supplies structure to JavaScript-heavy applications by providing <b>models</b> with
  300. key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
  301. <b>views</b> with declarative event handling, and connects it all to your
  302. existing application over a RESTful JSON interface.
  303. </p>
  304. <p>
  305. The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
  306. and the <a href="docs/backbone.html">annotated source code</a> is available,
  307. as well as an online <a href="test/test.html">test suite</a>, and
  308. <a href="examples/todos/index.html">example application</a>.
  309. </p>
  310. <p>
  311. You can report bugs and discuss features on the
  312. <a href="http://github.com/documentcloud/backbone/issues">issues page</a>,
  313. on Freenode in the <tt>#documentcloud</tt> channel,
  314. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  315. </p>
  316. <p>
  317. <i>
  318. Backbone is an open-source component of
  319. <a href="http://documentcloud.org/">DocumentCloud</a>.
  320. </i>
  321. </p>
  322. <h2 id="downloads">
  323. Downloads &amp; Dependencies
  324. <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
  325. </h2>
  326. <table>
  327. <tr>
  328. <td><a href="backbone.js">Development Version (0.3.3)</a></td>
  329. <td><i>35kb, Uncompressed with Comments</i></td>
  330. </tr>
  331. <tr>
  332. <td><a href="backbone-min.js">Production Version (0.3.3)</a></td>
  333. <td><i>3.9kb, Packed and Gzipped</i></td>
  334. </tr>
  335. </table>
  336. <p>
  337. Backbone's only hard dependency is
  338. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
  339. For RESTful persistence, and DOM manipulation with
  340. <a href="#View">Backbone.View</a>,
  341. it's highly recommended to include
  342. <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
  343. <a href="http://jquery.com">jQuery</a> or <a href="http://zeptojs.com/">Zepto</a>.
  344. </p>
  345. <h2 id="Introduction">Introduction</h2>
  346. <p>
  347. When working on a web application that involves a lot of JavaScript, one
  348. of the first things you learn is to stop tying your data to the DOM. It's all
  349. too easy to create JavaScript applications that end up as tangled piles of
  350. jQuery selectors and callbacks, all trying frantically to keep data in
  351. sync between the HTML UI, your JavaScript logic, and the database on your
  352. server. For rich client-side applications, a more structured approach
  353. is helpful.
  354. </p>
  355. <p>
  356. With Backbone, you represent your data as
  357. <a href="#Model">Models</a>, which can be created, validated, destroyed,
  358. and saved to the server. Whenever a UI action causes an attribute of
  359. a model to change, the model triggers a <i>"change"</i> event; all
  360. the <a href="#View">Views</a> that display the model's data are notified of the
  361. event, causing them to re-render. You don't have to write the glue
  362. code that looks into the DOM to find an element with a specific <i>id</i>,
  363. and update the HTML manually
  364. &mdash; when the model changes, the views simply update themselves.
  365. </p>
  366. <p>
  367. Many of the examples that follow are runnable. Click the <i>play</i> button
  368. to execute them.
  369. </p>
  370. <h2 id="Events">Backbone.Events</h2>
  371. <p>
  372. <b>Events</b> is a module that can be mixed in to any object, giving the
  373. object the ability to bind and trigger custom named events. Events do not
  374. have to be declared before they are bound, and may take passed arguments.
  375. For example:
  376. </p>
  377. <pre class="runnable">
  378. var object = {};
  379. _.extend(object, Backbone.Events);
  380. object.bind("alert", function(msg) {
  381. alert("Triggered " + msg);
  382. });
  383. object.trigger("alert", "an event");
  384. </pre>
  385. <p id="Events-bind">
  386. <b class="header">bind</b><code>object.bind(event, callback)</code>
  387. <br />
  388. Bind a <b>callback</b> function to an object. The callback will be invoked
  389. whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
  390. If you have a large number of different events on a page, the convention is to use colons to
  391. namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
  392. </p>
  393. <p>
  394. Callbacks bound to the special
  395. <tt>"all"</tt> event will be triggered when any event occurs, and are passed
  396. the name of the event as the first argument. For example, to proxy all events
  397. from one object to another:
  398. </p>
  399. <pre>
  400. proxy.bind("all", function(eventName) {
  401. object.trigger(eventName);
  402. });
  403. </pre>
  404. <p id="Events-unbind">
  405. <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
  406. <br />
  407. Remove a previously-bound <b>callback</b> function from an object. If no
  408. callback is specified, all callbacks for the <b>event</b> will be
  409. removed. If no event is specified, <i>all</i> event callbacks on the object
  410. will be removed.
  411. </p>
  412. <pre>
  413. object.unbind("change", onChange); // Removes just the onChange callback.
  414. object.unbind("change"); // Removes all "change" callbacks.
  415. object.unbind(); // Removes all callbacks on object.
  416. </pre>
  417. <p id="Events-trigger">
  418. <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
  419. <br />
  420. Trigger callbacks for the given <b>event</b>. Subsequent arguments to
  421. <b>trigger</b> will be passed along to the event callbacks.
  422. </p>
  423. <h2 id="Model">Backbone.Model</h2>
  424. <p>
  425. <b>Models</b> are the heart of any JavaScript application, containing
  426. the interactive data as well as a large part of the logic surrounding it:
  427. conversions, validations, computed properties, and access control. You
  428. extend <b>Backbone.Model</b> with your domain-specific methods, and
  429. <b>Model</b> provides a basic set of functionality for managing changes.
  430. </p>
  431. <p>
  432. The following is a contrived example, but it demonstrates defining a model
  433. with a custom method, setting an attribute, and firing an event keyed
  434. to changes in that specific attribute.
  435. After running this code once, <tt>sidebar</tt> will be
  436. available in your browser's console, so you can play around with it.
  437. </p>
  438. <pre class="runnable">
  439. var Sidebar = Backbone.Model.extend({
  440. promptColor: function() {
  441. var cssColor = prompt("Please enter a CSS color:");
  442. this.set({color: cssColor});
  443. }
  444. });
  445. window.sidebar = new Sidebar;
  446. sidebar.bind('change:color', function(model, color) {
  447. $('#sidebar').css({background: color});
  448. });
  449. sidebar.set({color: 'white'});
  450. sidebar.promptColor();
  451. </pre>
  452. <p id="Model-extend">
  453. <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
  454. <br />
  455. To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
  456. and provide instance <b>properties</b>, as well as optional
  457. <b>classProperties</b> to be attached directly to the constructor function.
  458. </p>
  459. <p>
  460. <b>extend</b> correctly sets up the prototype chain, so subclasses created
  461. with <b>extend</b> can be further extended and subclassed as far as you like.
  462. </p>
  463. <pre>
  464. var Note = Backbone.Model.extend({
  465. initialize: function() { ... },
  466. author: function() { ... },
  467. coordinates: function() { ... },
  468. allowedToEdit: function(account) {
  469. return true;
  470. }
  471. });
  472. var PrivateNote = Note.extend({
  473. allowedToEdit: function(account) {
  474. return account.owns(this);
  475. }
  476. });
  477. </pre>
  478. <p class="warning">
  479. Brief aside on <tt>super</tt>: JavaScript does not provide
  480. a simple way to call super &mdash; the function of the same name defined
  481. higher on the prototype chain. If you override a core function like
  482. <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
  483. parent object's implementation, you'll have to explicitly call it, along these lines:
  484. </p>
  485. <pre>
  486. var Note = Backbone.Model.extend({
  487. set: function(attributes, options) {
  488. Backbone.Model.prototype.set.call(this, attributes, options);
  489. ...
  490. }
  491. });
  492. </pre>
  493. <p id="Model-constructor">
  494. <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
  495. <br />
  496. When creating an instance of a model, you can pass in the initial values
  497. of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
  498. model. If you define an <b>initialize</b> function, it will be invoked when
  499. the model is created.
  500. </p>
  501. <pre>
  502. new Book({
  503. title: "One Thousand and One Nights",
  504. author: "Scheherazade"
  505. });
  506. </pre>
  507. <p id="Model-get">
  508. <b class="header">get</b><code>model.get(attribute)</code>
  509. <br />
  510. Get the current value of an attribute from the model. For example:
  511. <tt>note.get("title")</tt>
  512. </p>
  513. <p id="Model-escape">
  514. <b class="header">escape</b><code>model.escape(attribute)</code>
  515. <br />
  516. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  517. of a model's attribute. If you're interpolating data from the model into
  518. HTML, using <b>escape</b> to retrieve attributes will prevent
  519. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  520. </p>
  521. <pre class="runnable">
  522. var hacker = new Backbone.Model({
  523. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  524. });
  525. alert(hacker.escape('name'));
  526. </pre>
  527. <p id="Model-set">
  528. <b class="header">set</b><code>model.set(attributes, [options])</code>
  529. <br />
  530. Set a hash of attributes (one or many) on the model. If any of the attributes
  531. change the models state, a <tt>"change"</tt> event will be triggered, unless
  532. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  533. attributes are also triggered, and you can bind to those as well, for example:
  534. <tt>change:title</tt>, and <tt>change:content</tt>.
  535. </p>
  536. <pre>
  537. note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
  538. </pre>
  539. <p>
  540. If the model has a <a href="#Model-validate">validate</a> method,
  541. it will be validated before the attributes are set, no changes will
  542. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  543. You may also pass an <tt>error</tt>
  544. callback in the options, which will be invoked instead of triggering an
  545. <tt>"error"</tt> event, should validation fail.
  546. </p>
  547. <p id="Model-escape">
  548. <b class="header">escape</b><code>model.escape(attribute)</code>
  549. <br />
  550. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  551. of a model's attribute. If you're interpolating data from the model into
  552. HTML, using <b>escape</b> to retrieve attributes will prevent
  553. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  554. </p>
  555. <pre class="runnable">
  556. var hacker = new Backbone.Model({
  557. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  558. });
  559. alert(hacker.escape('name'));
  560. </pre>
  561. <p id="Model-has">
  562. <b class="header">has</b><code>model.has(attribute)</code>
  563. <br />
  564. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  565. value.
  566. </p>
  567. <pre>
  568. if (note.has("title")) {
  569. ...
  570. }
  571. </pre>
  572. <p id="Model-unset">
  573. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  574. <br />
  575. Remove an attribute by deleting it from the internal attributes hash.
  576. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  577. </p>
  578. <p id="Model-clear">
  579. <b class="header">clear</b><code>model.clear([options])</code>
  580. <br />
  581. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  582. <tt>silent</tt> is passed as an option.
  583. </p>
  584. <p id="Model-id">
  585. <b class="header">id</b><code>model.id</code>
  586. <br />
  587. A special property of models, the <b>id</b> is an arbitrary string
  588. (integer id or UUID). If you set the <b>id</b> in the
  589. attributes hash, it will be copied onto the model as a direct property.
  590. Models can be retrieved by id from collections, and the id is used to generate
  591. model URLs by default.
  592. </p>
  593. <p id="Model-cid">
  594. <b class="header">cid</b><code>model.cid</code>
  595. <br />
  596. A special property of models, the <b>cid</b> or client id is a unique identifier
  597. automatically assigned to all models when they're first created. Client ids
  598. are handy when the model has not yet been saved to the server, and does not
  599. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  600. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  601. </p>
  602. <p id="Model-attributes">
  603. <b class="header">attributes</b><code>model.attributes</code>
  604. <br />
  605. The <b>attributes</b> property is the internal hash containing the model's
  606. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  607. them directly. If you'd like to retrieve and munge a copy of the model's
  608. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  609. </p>
  610. <p id="Model-defaults">
  611. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  612. <br />
  613. The <b>defaults</b> hash (or function) can be used to specify the default
  614. attributes for your model. When creating an instance of the model,
  615. any unspecified attributes will be set to their default value.
  616. </p>
  617. <pre class="runnable">
  618. var Meal = Backbone.Model.extend({
  619. defaults: {
  620. "appetizer": "caesar salad",
  621. "entree": "ravioli",
  622. "dessert": "cheesecake"
  623. }
  624. });
  625. alert("Dessert will be " + (new Meal).get('dessert'));
  626. </pre>
  627. <p id="Model-toJSON">
  628. <b class="header">toJSON</b><code>model.toJSON()</code>
  629. <br />
  630. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  631. This can be used for persistence, serialization, or for augmentation before
  632. being handed off to a view. The name of this method is a bit confusing, as
  633. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  634. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  635. </p>
  636. <pre class="runnable">
  637. var artist = new Backbone.Model({
  638. firstName: "Wassily",
  639. lastName: "Kandinsky"
  640. });
  641. artist.set({birthday: "December 16, 1866"});
  642. alert(JSON.stringify(artist));
  643. </pre>
  644. <p id="Model-fetch">
  645. <b class="header">fetch</b><code>model.fetch([options])</code>
  646. <br />
  647. Refreshes the model's state from the server. Useful if the model has never
  648. been populated with data, or if you'd like to ensure that you have the
  649. latest server state. A <tt>"change"</tt> event will be triggered if the
  650. server's state differs from the current attributes. Accepts
  651. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  652. are passed <tt>(model, response)</tt> as arguments.
  653. </p>
  654. <pre>
  655. // Poll every 10 seconds to keep the channel model up-to-date.
  656. setInterval(function() {
  657. channel.fetch();
  658. }, 10000);
  659. </pre>
  660. <p id="Model-save">
  661. <b class="header">save</b><code>model.save([attributes], [options])</code>
  662. <br />
  663. Save a model to your database (or alternative persistence layer),
  664. by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
  665. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  666. you'd like to change -- keys that aren't mentioned won't be altered.
  667. If the model has a <a href="#Model-validate">validate</a>
  668. method, and validation fails, the model will not be saved. If the model
  669. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  670. (HTTP <tt>POST</tt>), if the model already
  671. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  672. </p>
  673. <p>
  674. In the following example, notice how because the model has never been
  675. saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
  676. </p>
  677. <pre class="runnable">
  678. Backbone.sync = function(method, model) {
  679. alert(method + ": " + JSON.stringify(model));
  680. };
  681. var book = new Backbone.Model({
  682. title: "The Rough Riders",
  683. author: "Theodore Roosevelt"
  684. });
  685. book.save();
  686. </pre>
  687. <p>
  688. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  689. options hash, which are passed <tt>(model, response)</tt> as arguments.
  690. The <tt>error</tt> callback will also be invoked if the model has a
  691. <tt>validate</tt> method, and validation fails. If a server-side
  692. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  693. an error response in text or JSON.
  694. </p>
  695. <pre>
  696. book.save({author: "F.D.R."}, {error: function(){ ... }});
  697. </pre>
  698. <p id="Model-destroy">
  699. <b class="header">destroy</b><code>model.destroy([options])</code>
  700. <br />
  701. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  702. request to <a href="#Sync">Backbone.sync</a>. Accepts
  703. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  704. Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
  705. through any collections that contain it.
  706. </p>
  707. <pre>
  708. book.destroy({success: function(model, response) {
  709. ...
  710. }});
  711. </pre>
  712. <p id="Model-validate">
  713. <b class="header">validate</b><code>model.validate(attributes)</code>
  714. <br />
  715. This method is left undefined, and you're encouraged to override it with
  716. your custom validation logic, if you have any that can be performed
  717. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  718. <tt>save</tt>, and is passed the attributes that are about to be updated.
  719. If the model and attributes are valid, don't return anything from <b>validate</b>;
  720. if the attributes are invalid, return an error of your choosing. It
  721. can be as simple as a string error message to be displayed, or a complete
  722. error object that describes the error programmatically. <tt>set</tt> and
  723. <tt>save</tt> will not continue if <b>validate</b> returns an error.
  724. Failed validations trigger an <tt>"error"</tt> event.
  725. </p>
  726. <pre class="runnable">
  727. var Chapter = Backbone.Model.extend({
  728. validate: function(attrs) {
  729. if (attrs.end < attrs.start) {
  730. return "can't end before it starts";
  731. }
  732. }
  733. });
  734. var one = new Chapter({
  735. title : "Chapter One: The Beginning"
  736. });
  737. one.bind("error", function(model, error) {
  738. alert(model.get("title") + " " + error);
  739. });
  740. one.set({
  741. start: 15,
  742. end: 10
  743. });
  744. </pre>
  745. <p>
  746. <tt>"error"</tt> events are useful for providing coarse-grained error
  747. messages at the model or collection level, but if you have a specific view
  748. that can better handle the error, you may override and suppress the event
  749. by passing an <tt>error</tt> callback directly:
  750. </p>
  751. <pre>
  752. account.set({access: "unlimited"}, {
  753. error: function(model, error) {
  754. alert(error);
  755. }
  756. });
  757. </pre>
  758. <p id="Model-url">
  759. <b class="header">url</b><code>model.url()</code>
  760. <br />
  761. Returns the relative URL where the model's resource would be located on
  762. the server. If your models are located somewhere else, override this method
  763. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  764. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  765. </p>
  766. <p>
  767. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  768. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  769. property, if all models of this class share a common root URL.
  770. A model with an id of <tt>101</tt>, stored in a
  771. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  772. would have this URL: <tt>"/documents/7/notes/101"</tt>
  773. </p>
  774. <p id="Model-urlRoot">
  775. <b class="header">urlRoot</b><code>model.urlRoot</code>
  776. <br />
  777. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  778. to enable the default <a href="#Model-url">url</a> function to generate
  779. URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
  780. </p>
  781. <pre class="runnable">
  782. var Book = Backbone.Model.extend({urlRoot : '/books'});
  783. var solaris = new Book({id: "1083-lem-solaris"});
  784. alert(solaris.url());
  785. </pre>
  786. <p id="Model-parse">
  787. <b class="header">parse</b><code>model.parse(response)</code>
  788. <br />
  789. <b>parse</b> is called whenever a model's data is returned by the
  790. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  791. The function is passed the raw <tt>response</tt> object, and should return
  792. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  793. default implementation is a no-op, simply passing through the JSON response.
  794. Override this if you need to work with a preexisting API, or better namespace
  795. your responses.
  796. </p>
  797. <p>
  798. If you're working with a Rails backend, you'll notice that Rails' default
  799. <tt>to_json</tt> implementation includes a model's attributes under a
  800. namespace. To disable this behavior for seamless Backbone integration, set:
  801. </p>
  802. <pre>
  803. ActiveRecord::Base.include_root_in_json = false
  804. </pre>
  805. <p id="Model-clone">
  806. <b class="header">clone</b><code>model.clone()</code>
  807. <br />
  808. Returns a new instance of the model with identical attributes.
  809. </p>
  810. <p id="Model-isNew">
  811. <b class="header">isNew</b><code>model.isNew()</code>
  812. <br />
  813. Has this model been saved to the server yet? If the model does not yet have
  814. an <tt>id</tt>, it is considered to be new.
  815. </p>
  816. <p id="Model-change">
  817. <b class="header">change</b><code>model.change()</code>
  818. <br />
  819. Manually trigger the <tt>"change"</tt> event.
  820. If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  821. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  822. when you're all finished.
  823. </p>
  824. <p id="Model-hasChanged">
  825. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  826. <br />
  827. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  828. is passed, returns <tt>true</tt> if that specific attribute has changed.
  829. </p>
  830. <pre>
  831. book.bind("change", function() {
  832. if (book.hasChanged("title")) {
  833. ...
  834. }
  835. });
  836. </pre>
  837. <p id="Model-changedAttributes">
  838. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  839. <br />
  840. Retrieve a hash of only the model's attributes that have changed. Optionally,
  841. an external <b>attributes</b> hash can be passed in, returning
  842. the attributes in that hash which differ from the model. This can be used
  843. to figure out which portions of a view should be updated, or what calls
  844. need to be made to sync the changes to the server.
  845. </p>
  846. <p id="Model-previous">
  847. <b class="header">previous</b><code>model.previous(attribute)</code>
  848. <br />
  849. During a <tt>"change"</tt> event, this method can be used to get the
  850. previous value of a changed attribute.
  851. </p>
  852. <pre class="runnable">
  853. var bill = new Backbone.Model({
  854. name: "Bill Smith"
  855. });
  856. bill.bind("change:name", function(model, name) {
  857. alert("Changed name from " + bill.previous("name") + " to " + name);
  858. });
  859. bill.set({name : "Bill Jones"});
  860. </pre>
  861. <p id="Model-previousAttributes">
  862. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  863. <br />
  864. Return a copy of the model's previous attributes. Useful for getting a
  865. diff between versions of a model, or getting back to a valid state after
  866. an error occurs.
  867. </p>
  868. <h2 id="Collection">Backbone.Collection</h2>
  869. <p>
  870. Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
  871. to be notified when any model in the collection has been modified,
  872. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  873. the collection from the server, and use a full suite of
  874. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  875. </p>
  876. <p>
  877. Any event that is triggered on a model in a collection will also be
  878. triggered on the collection directly, for convenience.
  879. This allows you to listen for changes to specific attributes in any
  880. model in a collection, for example:
  881. <tt>Documents.bind("change:selected", ...)</tt>
  882. </p>
  883. <p id="Collection-extend">
  884. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  885. <br />
  886. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  887. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  888. directly to the collection's constructor function.
  889. </p>
  890. <p id="Collection-model">
  891. <b class="header">model</b><code>collection.model</code>
  892. <br />
  893. Override this property to specify the model class that the collection
  894. contains. If defined, you can pass raw attributes objects (and arrays) to
  895. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  896. and <a href="#Collection-refresh">refresh</a>, and the attributes will be
  897. converted into a model of the proper type.
  898. </p>
  899. <pre>
  900. var Library = Backbone.Collection.extend({
  901. model: Book
  902. });
  903. </pre>
  904. <p id="Collection-constructor">
  905. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  906. <br />
  907. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  908. The collection's <a href="#Collection-comparator">comparator</a> function
  909. may be included as an option. If you define an <b>initialize</b> function, it will be
  910. invoked when the collection is created.
  911. </p>
  912. <pre>
  913. var tabs = new TabSet([tab1, tab2, tab3]);
  914. </pre>
  915. <p id="Collection-models">
  916. <b class="header">models</b><code>collection.models</code>
  917. <br />
  918. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  919. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  920. to access model objects, but occasionally a direct reference to the array
  921. is desired.
  922. </p>
  923. <p id="Collection-toJSON">
  924. <b class="header">toJSON</b><code>collection.toJSON()</code>
  925. <br />
  926. Return an array containing the attributes hash of each model in the
  927. collection. This can be used to serialize and persist the
  928. collection as a whole. The name of this method is a bit confusing, because
  929. it conforms to
  930. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  931. </p>
  932. <pre class="runnable">
  933. var collection = new Backbone.Collection([
  934. {name: "Tim", age: 5},
  935. {name: "Ida", age: 26},
  936. {name: "Rob", age: 55}
  937. ]);
  938. alert(JSON.stringify(collection));
  939. </pre>
  940. <p id="Collection-Underscore-Methods">
  941. <b class="header">Underscore Methods (25)</b>
  942. <br />
  943. Backbone proxies to <b>Underscore.js</b> to provide 25 iteration functions
  944. on <b>Backbone.Collection</b>. They aren't all documented here, but
  945. you can take a look at the Underscore documentation for the full details&hellip;
  946. </p>
  947. <ul>
  948. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  949. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  950. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  951. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  952. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  953. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  954. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  955. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  956. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  957. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  958. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  959. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  960. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  961. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  962. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  963. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  964. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  965. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  966. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  967. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  968. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  969. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  970. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  971. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  972. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  973. </ul>
  974. <pre>
  975. Books.each(function(book) {
  976. book.publish();
  977. });
  978. var titles = Books.map(function(book) {
  979. return book.get("title");
  980. });
  981. var publishedBooks = Books.filter(function(book) {
  982. return book.get("published") === true;
  983. });
  984. var alphabetical = Books.sortBy(function(book) {
  985. return book.author.get("name").toLowerCase();
  986. });
  987. </pre>
  988. <p id="Collection-add">
  989. <b class="header">add</b><code>collection.add(models, [options])</code>
  990. <br />
  991. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  992. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  993. <a href="#Collection-model">model</a> property is defined, you may also pass
  994. raw attributes objects, and have them be vivified as instances of the model.
  995. </p>
  996. <pre class="runnable">
  997. var ships = new Backbone.Collection;
  998. ships.bind("add", function(ship) {
  999. alert("Ahoy " + ship.get("name") + "!");
  1000. });
  1001. ships.add([
  1002. {name: "Flying Dutchman"},
  1003. {name: "Black Pearl"}
  1004. ]);
  1005. </pre>
  1006. <p id="Collection-remove">
  1007. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  1008. <br />
  1009. Remove a model (or an array of models) from the collection. Fires a
  1010. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  1011. to suppress.
  1012. </p>
  1013. <p id="Collection-get">
  1014. <b class="header">get</b><code>collection.get(id)</code>
  1015. <br />
  1016. Get a model from a collection, specified by <b>id</b>.
  1017. </p>
  1018. <pre>
  1019. var book = Library.get(110);
  1020. </pre>
  1021. <p id="Collection-getByCid">
  1022. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  1023. <br />
  1024. Get a model from a collection, specified by client id. The client id
  1025. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  1026. a model is created. Useful for models which have not yet been saved to
  1027. the server, and do not yet have true ids.
  1028. </p>
  1029. <p id="Collection-at">
  1030. <b class="header">at</b><code>collection.at(index)</code>
  1031. <br />
  1032. Get a model from a collection, specified by index. Useful if your collection
  1033. is sorted, and if your collection isn't sorted, <b>at</b> will still
  1034. retrieve models in insertion order.
  1035. </p>
  1036. <p id="Collection-length">
  1037. <b class="header">length</b><code>collection.length</code>
  1038. <br />
  1039. Like an array, a Collection maintains a <tt>length</tt> property, counting
  1040. the number of models it contains.
  1041. </p>
  1042. <p id="Collection-comparator">
  1043. <b class="header">comparator</b><code>collection.comparator</code>
  1044. <br />
  1045. By default there is no <b>comparator</b> function on a collection.
  1046. If you define a comparator, it will be used to maintain
  1047. the collection in sorted order. This means that as models are added,
  1048. they are inserted at the correct index in <tt>collection.models</tt>.
  1049. Comparator functions take a model and return a numeric or string value
  1050. by which the model should be ordered relative to others.
  1051. </p>
  1052. <p>
  1053. Note how even though all of the chapters in this example are added backwards,
  1054. they come out in the proper order:
  1055. </p>
  1056. <pre class="runnable">
  1057. var Chapter = Backbone.Model;
  1058. var chapters = new Backbone.Collection;
  1059. chapters.comparator = function(chapter) {
  1060. return chapter.get("page");
  1061. };
  1062. chapters.add(new Chapter({page: 9, title: "The End"}));
  1063. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1064. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1065. alert(chapters.pluck('title'));
  1066. </pre>
  1067. <p class="warning">
  1068. Brief aside: This comparator function is different than JavaScript's regular
  1069. "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
  1070. and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
  1071. </p>
  1072. <p id="Collection-sort">
  1073. <b class="header">sort</b><code>collection.sort([options])</code>
  1074. <br />
  1075. Force a collection to re-sort itself. You don't need to call this under
  1076. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1077. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1078. triggers the collection's <tt>"refresh"</tt> event, unless silenced by passing
  1079. <tt>{silent: true}</tt>
  1080. </p>
  1081. <p id="Collection-pluck">
  1082. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1083. <br />
  1084. Pluck an attribute from each model in the collection. Equivalent to calling
  1085. <tt>map</tt>, and returning a single attribute from the iterator.
  1086. </p>
  1087. <pre class="runnable">
  1088. var stooges = new Backbone.Collection([
  1089. new Backbone.Model({name: "Curly"}),
  1090. new Backbone.Model({name: "Larry"}),
  1091. new Backbone.Model({name: "Moe"})
  1092. ]);
  1093. var names = stooges.pluck("name");
  1094. alert(JSON.stringify(names));
  1095. </pre>
  1096. <p id="Collection-url">
  1097. <b class="header">url</b><code>collection.url or collection.url()</code>
  1098. <br />
  1099. Set the <b>url</b> property (or function) on a collection to reference
  1100. its location on the server. Models within the collection will use <b>url</b>
  1101. to construct URLs of their own.
  1102. </p>
  1103. <pre>
  1104. var Notes = Backbone.Collection.extend({
  1105. url: '/notes'
  1106. });
  1107. // Or, something more sophisticated:
  1108. var Notes = Backbone.Collection.extend({
  1109. url: function() {
  1110. return this.document.url() + '/notes';
  1111. }
  1112. });
  1113. </pre>
  1114. <p id="Collection-parse">
  1115. <b class="header">parse</b><code>collection.parse(response)</code>
  1116. <br />
  1117. <b>parse</b> is called by Backbone whenever a collection's models are
  1118. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1119. The function is passed the raw <tt>response</tt> object, and should return
  1120. the array of model attributes to be <a href="#Collection-add">added</a>
  1121. to the collection. The default implementation is a no-op, simply passing
  1122. through the JSON response. Override this if you need to work with a
  1123. preexisting API, or better namespace your responses.
  1124. </p>
  1125. <pre>
  1126. var Tweets = Backbone.Collection.extend({
  1127. // The Twitter Search API returns tweets under "results".
  1128. parse: function(response) {
  1129. return response.results;
  1130. }
  1131. });
  1132. </pre>
  1133. <p id="Collection-fetch">
  1134. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1135. <br />
  1136. Fetch the default set of models for this collection from the server,
  1137. refreshing the collection when they arrive. The <b>options</b> hash takes
  1138. <tt>success</tt> and <tt>error</tt>
  1139. callbacks which will be passed <tt>(collection, response)</tt> as arguments.
  1140. When the model data returns from the server, the collection will
  1141. <a href="#Collection-refresh">refresh</a>.
  1142. Delegates to <a href="#Sync">Backbone.sync</a>
  1143. under the covers, for custom persistence strategies.
  1144. The server handler for <b>fetch</b> requests should return a JSON array of
  1145. models.
  1146. </p>
  1147. <pre class="runnable">
  1148. Backbone.sync = function(method, model) {
  1149. alert(method + ": " + model.url);
  1150. };
  1151. var Accounts = new Backbone.Collection;
  1152. Accounts.url = '/accounts';
  1153. Accounts.fetch();
  1154. </pre>
  1155. <p>
  1156. If you'd like to add the incoming models to the current collection, instead
  1157. of replacing the collection's contents, pass <tt>{add: true}</tt> as an
  1158. option to <b>fetch</b>.
  1159. </p>
  1160. <p>
  1161. Note that <b>fetch</b> should not be used to populate collections on
  1162. page load &mdash; all models needed at load time should already be
  1163. <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
  1164. intended for lazily-loading models for interfaces that are not needed
  1165. immediately: for example, documents with collections of notes that may be
  1166. toggled open and closed.
  1167. </p>
  1168. <p id="Collection-refresh">
  1169. <b class="header">refresh</b><code>collection.refresh(models, [options])</code>
  1170. <br />
  1171. Adding and removing models one at a time is all well and good, but sometimes
  1172. you have so many models to change that you'd rather just update the collection
  1173. in bulk. Use <b>refresh</b> to replace a collection with a new list
  1174. of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
  1175. at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
  1176. </p>
  1177. <p>
  1178. Here's an example using <b>refresh</b> to bootstrap a collection during initial page load,
  1179. in a Rails application.
  1180. </p>
  1181. <pre>
  1182. &lt;script&gt;
  1183. Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
  1184. &lt;/script&gt;
  1185. </pre>
  1186. <p id="Collection-create">
  1187. <b class="header">create</b><code>collection.create(attributes, [options])</code>
  1188. <br />
  1189. Convenience to create a new instance of a model within a collection.
  1190. Equivalent to instantiating a model with a hash of attributes,
  1191. saving the model to the server, and adding the model to the set after being
  1192. successfully created. Returns
  1193. the model, or <tt>false</tt> if a validation error prevented the
  1194. model from being created. In order for this to work, your should set the
  1195. <a href="#Collection-model">model</a> property of the collection.
  1196. </p>
  1197. <pre>
  1198. var Library = Backbone.Collection.extend({
  1199. model: Book
  1200. });
  1201. var NYPL = new Library;
  1202. var othello = NYPL.create({
  1203. title: "Othello",
  1204. author: "William Shakespeare"
  1205. });
  1206. </pre>
  1207. <h2 id="Controller">Backbone.Controller</h2>
  1208. <p>
  1209. Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
  1210. in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
  1211. <b>Backbone.Controller</b> provides methods for routing client-side URL
  1212. fragments, and connecting them to actions and events.
  1213. </p>
  1214. <p class="warning">
  1215. Backbone controllers do not yet make use of HTML5 <b>pushState</b> and
  1216. <b>replaceState</b>. Currently, <b>pushState</b> and <b>replaceState</b>
  1217. need special handling on the server-side, cause you to mint duplicate URLs,
  1218. and have an incomplete API. We may start supporting them in the future
  1219. when these issues have been resolved.
  1220. </p>
  1221. <p>
  1222. During page load, after your application has finished creating all of its controllers,
  1223. be sure to call <tt>Backbone.history.start()</tt> to route the initial URL.
  1224. </p>
  1225. <p id="Controller-extend">
  1226. <b class="header">extend</b><code>Backbone.Controller.extend(properties, [classProperties])</code>
  1227. <br />
  1228. Get started by creating a custom controller class. You'll
  1229. want to define actions that are triggered when certain URL fragments are
  1230. matched, and provide a <a href="#Controller-routes">routes</a> hash
  1231. that pairs routes to actions.
  1232. </p>
  1233. <pre>
  1234. var Workspace = Backbone.Controller.extend({
  1235. routes: {
  1236. "help": "help", // #help
  1237. "search/:query": "search", // #search/kiwis
  1238. "search/:query/p:page": "search" // #search/kiwis/p7
  1239. },
  1240. help: function() {
  1241. ...
  1242. },
  1243. search: function(query, page) {
  1244. ...
  1245. }
  1246. });
  1247. </pre>
  1248. <p id="Controller-routes">
  1249. <b class="header">routes</b><code>controller.routes</code>
  1250. <br />
  1251. The routes hash maps URLs with parameters to functions on your controller,
  1252. similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
  1253. Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
  1254. component between slashes; and splat parts <tt>*splat</tt>, which can match
  1255. any number of URL components.
  1256. </p>
  1257. <p>
  1258. For example, a route of <tt>"search/:query/p:page"</tt> will match
  1259. a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
  1260. and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
  1261. match <tt>#file/nested/folder/file.txt</tt>,
  1262. passing <tt>"nested/folder/file.txt"</tt> to the action.
  1263. </p>
  1264. <p>
  1265. When the visitor presses the back button, or enters a URL, and a particular
  1266. route is matched, the name of the action will be fired as an
  1267. <a href="#Events">event</a>, so that other objects can listen to the controller,
  1268. and be notified. In the following example, visiting <tt>#help/uploading</tt>
  1269. will fire a <tt>route:help</tt> event from the controller.
  1270. </p>
  1271. <pre>
  1272. routes: {
  1273. "help/:page": "help",
  1274. "download/*path": "download",
  1275. "folder/:name": "openFolder",
  1276. "folder/:name-:mode": "openFolder"
  1277. }
  1278. </pre>
  1279. <pre>
  1280. controller.bind("route:help", function(page) {
  1281. ...
  1282. });
  1283. </pre>
  1284. <p id="Controller-constructor">
  1285. <b class="header">constructor / initialize</b><code>new Controller([options])</code>
  1286. <br />
  1287. When creating a new controller, you may pass its
  1288. <a href="#Controller-routes">routes</a> hash directly as an option, if you
  1289. choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
  1290. function, if defined.
  1291. </p>
  1292. <p id="Controller-route">
  1293. <b class="header">route</b><code>controller.route(route, name, callback)</code>
  1294. <br />
  1295. Manually create a route for the controller, The <tt>route</tt> argument may
  1296. be a <a href="#Controller-routes">routing string</a> or regular expression.
  1297. Each matching capture from the route or regular expression will be passed as
  1298. an argument to the callback. The <tt>name</tt> argument will be triggered as
  1299. a <tt>"route:name"</tt> event whenever the route is matched.
  1300. </p>
  1301. <pre>
  1302. initialize: function(options) {
  1303. // Matches #page/10, passing "10"
  1304. this.route("page/:number", "page", function(number){ ... });
  1305. // Matches /117-a/b/c/open, passing "117-a/b/c"
  1306. this.route(/^(.*?)\/open$/, "open", function(id){ ... });
  1307. }
  1308. </pre>
  1309. <p id="Controller-saveLocation">
  1310. <b class="header">saveLocation</b><code>controller.saveLocation(fragment)</code>
  1311. <br />
  1312. Whenever you reach a point in your application that you'd like to save
  1313. as a URL, call <b>saveLocation</b> in order to update the URL fragment
  1314. without triggering a <tt>hashchange</tt> event. (If you would prefer to
  1315. trigger the event and routing, you can just set the hash directly.)
  1316. </p>
  1317. <pre>
  1318. openPage: function(pageNumber) {
  1319. this.document.pages.at(pageNumber).open();
  1320. this.saveLocation("page/" + pageNumber);
  1321. }
  1322. </pre>
  1323. <h2 id="History">Backbone.history</h2>
  1324. <p>
  1325. <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
  1326. events, match the appropriate route, and trigger callbacks. You shouldn't
  1327. ever have to create one of these yourself &mdash; you should use the reference
  1328. to <tt>Backbone.history</tt> that will be created for you automatically if you make use
  1329. of <a href="#Controller">Controllers</a> with <a href="#Controller-routes">routes</a>.
  1330. </p>
  1331. <p id="History-start">
  1332. <b class="header">start</b><code>Backbone.history.start()</code>
  1333. <br />
  1334. When all of your <a href="#Controller">Controllers</a> have been created,
  1335. and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
  1336. to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
  1337. </p>
  1338. <pre>
  1339. $(function(){
  1340. new WorkspaceController();
  1341. new HelpPaneController();
  1342. Backbone.history.start();
  1343. });
  1344. </pre>
  1345. <h2 id="Sync">Backbone.sync</h2>
  1346. <p>
  1347. <b>Backbone.sync</b> is the function the Backbone calls every time it
  1348. attempts to read or save a model to the server. By default, it uses
  1349. <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request. You can override
  1350. it in order to use a different persistence strategy, such as WebSockets,
  1351. XML transport, or Local Storage.
  1352. </p>
  1353. <p>
  1354. The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, success, error)</tt>
  1355. </p>
  1356. <ul>
  1357. <li><b>method</b> the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
  1358. <li><b>model</b> the model to be saved (or collection to be read)</li>
  1359. <li><b>success({model: ...})</b> a callback that should be fired if the request works</li>
  1360. <li><b>error({model: ...})</b> a callback that should be fired if the request fails</li>
  1361. </ul>
  1362. <p>
  1363. With the default implementation, when <b>Backbone.sync</b> sends up a request to save
  1364. a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
  1365. with content-type <tt>application/json</tt>. When returning a JSON response,
  1366. send down the attributes of the model that have been changed by the server, and need
  1367. to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
  1368. (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
  1369. of model attribute objects.
  1370. </p>
  1371. <p>
  1372. The default <b>sync</b> handler maps CRUD to REST like so:
  1373. </p>
  1374. <ul>
  1375. <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
  1376. <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
  1377. <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
  1378. <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
  1379. </ul>
  1380. <p>
  1381. As an example, a Rails handler responding to an <tt>"update"</tt> call from
  1382. <tt>Backbone</tt> might look like this: <i>(In real code, never use
  1383. </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
  1384. you allow to be changed.)</i>
  1385. </p>
  1386. <pre>
  1387. def update
  1388. account = Account.find params[:id]
  1389. account.update_attributes params
  1390. render :json => account
  1391. end
  1392. </pre>
  1393. <p>
  1394. One more tip for Rails integration is to disable the default namespacing for
  1395. <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
  1396. </p>
  1397. <p id="Sync-emulateHTTP">
  1398. <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
  1399. <br />
  1400. If you want to work with a legacy web server that doesn't support Backbones's
  1401. default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
  1402. Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
  1403. a HTTP <tt>POST</tt>, and pass them under the <tt>_method</tt> parameter. Setting this option
  1404. will also set an <tt>X-HTTP-Method-Override</tt> header with the true method.
  1405. </p>
  1406. <pre>
  1407. Backbone.emulateHTTP = true;
  1408. model.save(); // POST to "/collection/id", with "_method=PUT" + header.
  1409. </pre>
  1410. <p id="Sync-emulateJSON">
  1411. <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
  1412. <br />
  1413. If you're working with a legacy web server that can't handle requests
  1414. encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
  1415. will cause the JSON to be serialized under a <tt>model</tt> parameter, and
  1416. the request to be made with a <tt>application/x-www-form-urlencoded</tt>
  1417. mime type, as if from an HTML form.
  1418. </p>
  1419. <h2 id="View">Backbone.View</h2>
  1420. <p>
  1421. Backbone views are almost more convention than they are code &mdash; they
  1422. don't determine anything about your HTML or CSS for you, and can be used
  1423. with any JavaScript templating library.
  1424. The general idea is to organize your interface into logical views,
  1425. backed by models, each of which can be updated independently when the
  1426. model changes, without having to redraw the page. Instead of digging into
  1427. a JSON object, looking up an element in the DOM, and updating the HTML by hand,
  1428. you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
  1429. event &mdash; and now everywhere that
  1430. model data is displayed in the UI, it is always immediately up to date.
  1431. </p>
  1432. <p id="View-extend">
  1433. <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
  1434. <br />
  1435. Get started with views by creating a custom view class. You'll want to
  1436. override the <a href="#View-render">render</a> function, specify your
  1437. declarative <a href="#View-delegateEvents">events</a>, and perhaps the
  1438. <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
  1439. element.
  1440. </p>
  1441. <pre>
  1442. var DocumentRow = Backbone.View.extend({
  1443. tagName: "li",
  1444. className: "document-row",
  1445. events: {
  1446. "click .icon": "open",
  1447. "click .button.edit": "openEditDialog",
  1448. "click .button.delete": "destroy"
  1449. },
  1450. initialize: function() {
  1451. _.bindAll(this, "render");
  1452. },
  1453. render: function() {
  1454. ...
  1455. }
  1456. });
  1457. </pre>
  1458. <p id="View-constructor">
  1459. <b class="header">constructor / initialize</b><code>new View([options])</code>
  1460. <br />
  1461. When creating a new View, the options you pass are attached to the view
  1462. as <tt>this.options</tt>, for future reference. There are several special
  1463. options that, if passed, will be attached directly to the view:
  1464. <tt>model</tt>, <tt>collection</tt>,
  1465. <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, and <tt>tagName</tt>.
  1466. If the view defines an <b>initialize</b> function, it will be called when
  1467. the view is first created. If you'd like to create a view that references
  1468. an element <i>already</i> in the DOM, pass in the element as an option:
  1469. <tt>new View({el: existingElement})</tt>
  1470. </p>
  1471. <pre>
  1472. var doc = Documents.first();
  1473. new DocumentRow({
  1474. model: doc,
  1475. id: "document-row-" + doc.id
  1476. });
  1477. </pre>
  1478. <p id="View-el">
  1479. <b class="header">el</b><code>view.el</code>
  1480. <br />
  1481. All views have a DOM element at all times (the <b>el</b> property),
  1482. whether they've already been inserted into the page or not. In this
  1483. fashion, views can be rendered at any time, and inserted into the DOM all
  1484. at once, in order to get high-performance UI rendering with as few
  1485. reflows and repaints as possible. <tt>this.el</tt> is created from the
  1486. view's <tt>tagName</tt>, <tt>className</tt>, and <tt>id</tt> properties,
  1487. if specified. If not, <b>el</b> is an empty <tt>div</tt>.
  1488. </p>
  1489. <p>
  1490. You may assign <b>el</b> directly if the view is being
  1491. created for an element that already exists in the DOM. Use either a
  1492. reference to a real DOM element, or a css selector string.
  1493. </p>
  1494. <pre class="runnable">
  1495. var ItemView = Backbone.View.extend({
  1496. tagName: 'li'
  1497. });
  1498. var BodyView = Backbone.View.extend({
  1499. el: 'body'
  1500. });
  1501. var item = new ItemView();
  1502. var body = new BodyView();
  1503. alert(item.el + ' ' + body.el);
  1504. </pre>
  1505. <p id="View-dollar">
  1506. <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
  1507. <br />
  1508. If jQuery or Zepto is included on the page, each view has a
  1509. <b>$</b> function that runs queries scoped within the view's element. If you use this
  1510. scoped jQuery function, you don't have to use model ids as part of your query
  1511. to pull out specific elements in a list, and can rely much more on HTML class
  1512. attributes. It's equivalent to running: <tt>$(selector, this.el)</tt>
  1513. </p>
  1514. <pre>
  1515. ui.Chapter = Backbone.View.extend({
  1516. serialize : function() {
  1517. return {
  1518. title: this.$(".title").text(),
  1519. start: this.$(".start-page").text(),
  1520. end: this.$(".end-page").text()
  1521. };
  1522. }
  1523. });
  1524. </pre>
  1525. <p id="View-render">
  1526. <b class="header">render</b><code>view.render()</code>
  1527. <br />
  1528. The default implementation of <b>render</b> is a no-op. Override this
  1529. function with your code that renders the view template from model data,
  1530. and updates <tt>this.el</tt> with the new HTML. A good
  1531. convention is to <tt>return this</tt> at the end of <b>render</b> to
  1532. enable chained calls.
  1533. </p>
  1534. <pre>
  1535. var Bookmark = Backbone.View.extend({
  1536. render: function() {
  1537. $(this.el).html(this.template(this.model.toJSON()));
  1538. return this;
  1539. }
  1540. });
  1541. </pre>
  1542. <p>
  1543. Backbone is agnostic with respect to your preferred method of HTML templating.
  1544. Your <b>render</b> function could even munge together an HTML string, or use
  1545. <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
  1546. choosing a nice JavaScript templating library.
  1547. <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
  1548. <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
  1549. <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
  1550. Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
  1551. <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
  1552. is available, and is an excellent choice if you've already XSS-sanitized
  1553. your interpolated data.
  1554. </p>
  1555. <p>
  1556. Whatever templating strategy you end up with, it's nice if you <i>never</i>
  1557. have to put strings of HTML in your JavaScript. At DocumentCloud, we
  1558. use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
  1559. to package up JavaScript templates stored in <tt>/app/views</tt> as part
  1560. of our main <tt>core.js</tt> asset package.
  1561. </p>
  1562. <p id="View-remove">
  1563. <b class="header">remove</b><code>view.remove()</code>
  1564. <br />
  1565. Convenience function for removing the view from the DOM. Equivalent to calling
  1566. <tt>$(view.el).remove();</tt>
  1567. </p>
  1568. <p id="View-make">
  1569. <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
  1570. <br />
  1571. Convenience function for creating a DOM element of the given type (<b>tagName</b>),
  1572. with optional attributes and HTML content. Used internally to create the
  1573. initial <tt>view.el</tt>.
  1574. </p>
  1575. <pre class="runnable">
  1576. var view = new Backbone.View;
  1577. var el = view.make("b", {className: "bold"}, "Bold! ");
  1578. $("#make-demo").append(el);
  1579. </pre>
  1580. <div id="make-demo"></div>
  1581. <p id="View-delegateEvents">
  1582. <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
  1583. <br />
  1584. Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
  1585. for DOM events within a view.
  1586. If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
  1587. as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
  1588. Omitting the <tt>selector</tt> causes the event to be bound to the view's
  1589. root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
  1590. within the View's constructor for you, so if you have a simple <tt>events</tt>
  1591. hash, all of your DOM events will always already be connected, and you will
  1592. never have to call this function yourself.
  1593. </p>
  1594. <p>
  1595. Using <b>delegateEvents</b> provides a number of advantages over manually
  1596. using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
  1597. callbacks are bound to the view before being handed off to jQuery, so when
  1598. the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
  1599. <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
  1600. hash, all callbacks are removed and delegated afresh &mdash; useful for
  1601. views which need to behave differently when in different modes.
  1602. </p>
  1603. <p>
  1604. A view that displays a document in a search result might look
  1605. something like this:
  1606. </p>
  1607. <pre>
  1608. var DocumentView = Backbone.View.extend({
  1609. events: {
  1610. "dblclick" : "open",
  1611. "click .icon.doc" : "select",
  1612. "contextmenu .icon.doc" : "showMenu",
  1613. "click .show_notes" : "toggleNotes",
  1614. "click .title .lock" : "editAccessLevel",
  1615. "mouseover .title .date" : "showTooltip"
  1616. },
  1617. render: function() {
  1618. $(this.el).html(this.template(this.model.toJSON()));
  1619. return this;
  1620. },
  1621. open: function() {
  1622. window.open(this.model.get("viewer_url"));
  1623. },
  1624. select: function() {
  1625. this.model.set({selected: true});
  1626. },
  1627. ...
  1628. });
  1629. </pre>
  1630. <h2 id="Utility">Backbone Utilities</h2>
  1631. <p>
  1632. </p>
  1633. <p id="Utility-noConflict">
  1634. <b class="header">noConflict</b><code>var backbone = Backbone.noConflict();</code>
  1635. <br />
  1636. Returns the <tt>Backbone</tt> object back to its original value. You can
  1637. use the return value of <tt>Backbone.noConflict()</tt> to keep a local
  1638. reference to Backbone. Useful for embedding Backbone on third-party
  1639. websites, where you don't want to clobber the existing Backbone.
  1640. </p>
  1641. <pre>
  1642. var localBackbone = Backbone.noConflict();
  1643. var model = localBackbone.Model.extend(...);
  1644. </pre>
  1645. <h2 id="examples">Examples</h2>
  1646. <p id="examples-todos">
  1647. <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
  1648. <a href="examples/todos/index.html">Todo List application</a>
  1649. that is bundled in the repository as Backbone example. If you're wondering
  1650. where to get started with Backbone in general, take a moment to
  1651. <a href="docs/todos.html">read through the annotated source</a>. The app uses a
  1652. <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
  1653. to transparently save all of your todos within your browser, instead of
  1654. sending them to a server. Jérôme also has a version hosted at
  1655. <a href="http://localtodos.com/">localtodos.com</a> that uses a
  1656. <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
  1657. instead of jQuery.
  1658. </p>
  1659. <div style="text-align: center;">
  1660. <a href="examples/todos/index.html">
  1661. <img src="docs/images/todos.png" alt="Todos" class="example_image" />
  1662. </a>
  1663. </div>
  1664. <p id="examples-documentcloud">
  1665. The <a href="http://www.documentcloud.org/public/#search/">DocumentCloud workspace</a>
  1666. is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
  1667. <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
  1668. </p>
  1669. <div style="text-align: center;">
  1670. <a href="http://www.documentcloud.org/public/#search/">
  1671. <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" class="example_image" />
  1672. </a>
  1673. </div>
  1674. <p id="examples-basecamp">
  1675. <a href="http://37signals.com/">37Signals</a> used Backbone.js to create
  1676. <a href="http://basecamphq.com/mobile">Basecamp Mobile</a>, the mobile version
  1677. of their popular project management software. You can access all your Basecamp
  1678. projects, post new messages, and comment on milestones (all represented
  1679. internally as Backbone.js models).
  1680. </p>
  1681. <div style="text-align: center;">
  1682. <a href="http://basecamphq.com/mobile">
  1683. <img src="docs/images/basecamp-mobile.png" alt="Basecamp Mobile" class="example_image" />
  1684. </a>
  1685. </div>
  1686. <p id="examples-flow">
  1687. <a href="http://www.metalabdesign.com/">MetaLab</a> used Backbone.js to create
  1688. <a href="http://www.getflow.com/">Flow</a>, a task management app for teams. The
  1689. workspace relies on Backbone.js to construct task views, activities, accounts,
  1690. folders, projects, and tags. You can see the internals under <tt>window.Flow</tt>.
  1691. </p>
  1692. <div style="text-align: center;">
  1693. <a href="http://www.getflow.com/">
  1694. <img src="docs/images/flow.png" alt="Flow" class="example_image" />
  1695. </a>
  1696. </div>
  1697. <p id="examples-tilemill">
  1698. Our fellow
  1699. <a href="http://www.newschallenge.org/">Knight Foundation News Challenge</a>
  1700. winners, <a href="http://mapbox.com/">MapBox</a>, created an open-source
  1701. map design studio with Backbone.js:
  1702. <a href="http://mapbox.github.com/tilemill/">TileMill</a>.
  1703. TileMill lets you manage map layers based on shapefiles and rasters, and
  1704. edit their appearance directly in the browser with the
  1705. <a href="https://github.com/mapbox/carto">Carto styling language</a>.
  1706. </p>
  1707. <div style="text-align: center;">
  1708. <a href="http://mapbox.github.com/tilemill/">
  1709. <img src="docs/images/tilemill.png" alt="TileMill" class="example_image" />
  1710. </a>
  1711. </div>
  1712. <p id="examples-soundcloud">
  1713. <a href="http://soundcloud.com">SoundCloud</a> is the best sound sharing
  1714. platform on the internet, and Backbone.js provides the foundation for
  1715. <a href="http://m.soundcloud.com">Mobile SoundCloud</a>. The project uses
  1716. the public SoundCloud <a href="http://soundcloud.com/developers">API</a>
  1717. as a data source (channeled through a nginx proxy),
  1718. <a href="http://api.jquery.com/category/plugins/templates/">jQuery templates</a>
  1719. for the rendering, <a href="http://docs.jquery.com/Qunit">Qunit
  1720. </a> and <a href="http://code.google.com/p/phantomjs/">PhantomJS</a> for
  1721. the testing suite. The JS code, templates and CSS are built for the
  1722. production deployment with various Node.js tools like
  1723. <a href="https://github.com/dsimard/ready.js">ready.js</a>,
  1724. <a href="https://github.com/mde/node-jake">Jake</a>,
  1725. <a href="https://github.com/tmpvar/jsdom">jsdom</a>.
  1726. The <b>Backbone.History</b> was modified to support the HTML5 <tt>history.pushState</tt>.
  1727. <b>Backbone.sync</b> was extended with an additional SessionStorage based cache
  1728. layer.
  1729. </p>
  1730. <div style="text-align: center;">
  1731. <a href="http://m.soundcloud.com">
  1732. <img src="docs/images/soundcloud.png" alt="SoundCloud" class="example_image" />
  1733. </a>
  1734. </div>
  1735. <p id="examples-instagreat">
  1736. <a href="http://twitter.com/elliottkember">Elliott Kember</a> and
  1737. <a href="http://twitter.com/dizzyup">Hector Simpson</a> built
  1738. <a href="http://instagre.at">Insta-great!</a>
  1739. - a fun way to explore popular photos and interact with
  1740. <a href="http://instagram.com/">Instagram</a> on the web.
  1741. Elliott says, "Backbone.js and Coffeescript were insanely useful for
  1742. writing clean, consistent UI code and keeping everything modular and
  1743. readable, even through several code refactors. I'm in love."
  1744. </p>
  1745. <div style="text-align: center;">
  1746. <a href="http://instagre.at">
  1747. <img src="docs/images/instagreat.png" alt="instagre.at" class="example_image" />
  1748. </a>
  1749. </div>
  1750. <p id="examples-quietwrite">
  1751. <a href="http://www.twitter.com/jamesjyu">James Yu</a> used Backbone.js to
  1752. create <a href="http://www.quietwrite.com/">QuietWrite</a>, an app
  1753. that gives writers a clean and quiet interface to concentrate on the text itself.
  1754. The editor relies on Backbone to persist document data to the server. He
  1755. followed up with a Backbone.js + Rails tutorial that describes how to implement
  1756. <a href="http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/">CloudEdit, a simple document editing app</a>.
  1757. </p>
  1758. <div style="text-align: center;">
  1759. <a href="http://www.quietwrite.com/">
  1760. <img src="docs/images/quietwrite.png" alt="QuietWrite" class="example_image" />
  1761. </a>
  1762. </div>
  1763. <p id="examples-tzigla">
  1764. <a href="http://twitter.com/evilchelu">Cristi Balan</a> and
  1765. <a href="http://dira.ro">Irina Dumitrascu</a> created
  1766. <a href="http://tzigla.com">Tzigla</a>, a collaborative drawing
  1767. application where artists make tiles that connect to each other to
  1768. create <a href="http://tzigla.com/boards/1">surreal drawings</a>.
  1769. Backbone models help organize the code, controllers provide
  1770. <a href="http://tzigla.com/boards/1#!/tiles/2-2">bookmarkable deep links</a>,
  1771. and the views are rendered with
  1772. <a href="https://github.com/creationix/haml-js">haml.js</a> and
  1773. <a href="http://zeptojs.com/">Zepto</a>.
  1774. Tzigla is written in Ruby (Rails) on the backend, and
  1775. <a href="http://coffeescript.org">CoffeeScript</a> on the frontend, with
  1776. <a href="http://documentcloud.github.com/jammit/">Jammit</a>
  1777. prepackaging the static assets.
  1778. </p>
  1779. <div style="text-align: center;">
  1780. <a href="http://www.tzigla.com/">
  1781. <img src="docs/images/tzigla.png" alt="Tzigla" class="example_image" />
  1782. </a>
  1783. </div>
  1784. <p id="examples-substance">
  1785. Michael Aufreiter is building an open source document authoring and
  1786. publishing engine: <a href="http://substance.io">Substance</a>.
  1787. Substance makes use of Backbone.View and Backbone.Controller, while
  1788. Backbone plays well together with
  1789. <a href="http://github.com/michael/data">Data.js</a>, which is used for
  1790. data persistence.
  1791. </p>
  1792. <div style="text-align: center;">
  1793. <a href="http://substance.io/">
  1794. <img src="docs/images/substance.png" alt="Substance" class="example_image" />
  1795. </a>
  1796. </div>
  1797. <h2 id="faq">F.A.Q.</h2>
  1798. <p id="FAQ-events">
  1799. <b class="header">Catalog of Events</b>
  1800. <br />
  1801. Here's a list of all of the built-in events that Backbone.js can fire.
  1802. You're also free to trigger your own events on Models and Views as you
  1803. see fit.
  1804. </p>
  1805. <ul>
  1806. <li><b>"add"</b> (model, collection) &mdash; when a model is added to a collection. </li>
  1807. <li><b>"remove"</b> (model, collection) &mdash; when a model is removed from a collection. </li>
  1808. <li><b>"refresh"</b> (collection) &mdash; when the collection's entire contents have been replaced. </li>
  1809. <li><b>"change"</b> (model, collection) &mdash; when a model's attributes have changed. </li>
  1810. <li><b>"change:[attribute]"</b> (model, collection) &mdash; when a specific attribute has been updated. </li>
  1811. <li><b>"destrooy"</b> (model, collection) &mdash; when a model is <a href="#Model-destroy">destroyed</a>. </li>
  1812. <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>
  1813. <li><b>"route:[name]"</b> (controller) &mdash; when one of a controller's routes has matched. </li>
  1814. <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
  1815. </ul>
  1816. <p id="FAQ-nested">
  1817. <b class="header">Nested Models &amp; Collections</b>
  1818. <br />
  1819. It's common to nest collections inside of models with Backbone. For example,
  1820. consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
  1821. One nice pattern for handling this is have a <tt>this.messages</tt> collection
  1822. for each mailbox, enabling the lazy-loading of messages, when the mailbox
  1823. is first opened ... perhaps with <tt>MessageList</tt> views listening for
  1824. <tt>"add"</tt> and <tt>"remove"</tt> events.
  1825. </p>
  1826. <pre>
  1827. var Mailbox = Backbone.Model.extend({
  1828. initialize: function() {
  1829. this.messages = new Messages;
  1830. this.messages.url = '/mailbox/' + this.id + '/messages';
  1831. this.messages.bind("refresh", this.updateCounts);
  1832. },
  1833. ...
  1834. });
  1835. var Inbox = new Mailbox;
  1836. // And then, when the Inbox is opened:
  1837. Inbox.messages.fetch();
  1838. </pre>
  1839. <p id="FAQ-bootstrap">
  1840. <b class="header">Loading Bootstrapped Models</b>
  1841. <br />
  1842. When your app first loads, it's common to have a set of initial models that
  1843. you know you're going to need, in order to render the page. Instead of
  1844. firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
  1845. a nicer pattern is to have their data already bootstrapped into the page.
  1846. You can then use <a href="#Collection-refresh">refresh</a> to populate your
  1847. collections with the initial data. At DocumentCloud, in the
  1848. <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
  1849. workspace, we do something along these lines:
  1850. </p>
  1851. <pre>
  1852. &lt;script&gt;
  1853. Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
  1854. Projects.refresh(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
  1855. &lt;/script&gt;
  1856. </pre>
  1857. <p id="FAQ-mvc">
  1858. <b class="header">How does Backbone relate to "traditional" MVC?</b>
  1859. <br />
  1860. Different implementations of the
  1861. <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
  1862. pattern tend to disagree about the definition of a controller. If it helps any, in
  1863. Backbone, the <a href="#View">View</a> class can also be thought of as a
  1864. kind of controller, dispatching events that originate from the UI, with
  1865. the HTML template serving as the true view. We call it a View because it
  1866. represents a logical chunk of UI, responsible for the contents of a single
  1867. DOM element.
  1868. </p>
  1869. <p id="FAQ-this">
  1870. <b class="header">Binding "this"</b>
  1871. <br />
  1872. Perhaps the single most common JavaScript "gotcha" is the fact that when
  1873. you pass a function as a callback, it's value for <tt>this</tt> is lost. With
  1874. Backbone, when dealing with <a href="#Events">events</a> and callbacks,
  1875. you'll often find it useful to rely on
  1876. <a href="http://documentcloud.github.com/underscore/#bind">_.bind</a> and
  1877. <a href="http://documentcloud.github.com/underscore/#bindAll">_.bindAll</a>
  1878. from Underscore.js. <tt>_.bind</tt> takes a function and an object to be
  1879. used as <tt>this</tt>, any time the function is called in the future.
  1880. <tt>_.bindAll</tt> takes an object and a list of method names: each method
  1881. in the list will be bound to the object, so that it's <tt>this</tt> may
  1882. not change. For example, in a <a href="#View">View</a> that listens for
  1883. changes to a collection...
  1884. </p>
  1885. <pre>
  1886. var MessageList = Backbone.View.extend({
  1887. initialize: function() {
  1888. _.bindAll(this, "addMessage", "removeMessage", "render");
  1889. var messages = this.collection;
  1890. messages.bind("refresh", this.render);
  1891. messages.bind("add", this.addMessage);
  1892. messages.bind("remove", this.removeMessage);
  1893. }
  1894. });
  1895. // Later, in the app...
  1896. Inbox.messages.add(newMessage);
  1897. </pre>
  1898. <p id="FAQ-rias">
  1899. <b class="header">
  1900. How is Backbone different than
  1901. <a href="http://www.sproutcore.com/">SproutCore</a> or
  1902. <a href="http://cappuccino.org/">Cappuccino</a>?
  1903. </b>
  1904. <br />
  1905. This question is frequently asked, and all three projects apply general
  1906. <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
  1907. principles to JavaScript applications. However, there isn't much basis
  1908. for comparison. SproutCore and Cappuccino provide rich UI widgets, vast
  1909. core libraries, and determine the structure of your HTML for you.
  1910. Both frameworks measure in the hundreds of kilobytes when packed and
  1911. gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser
  1912. &mdash; there's a lot of room underneath for libraries of a more moderate scope.
  1913. Backbone is a <i>4 kilobyte</i> include that provides
  1914. just the core concepts of models, events, collections, views, controllers,
  1915. and persistence.
  1916. </p>
  1917. <h2 id="changelog">Change Log</h2>
  1918. <p>
  1919. <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
  1920. Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
  1921. jQuery, as a framework for DOM manipulation and Ajax support.
  1922. Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
  1923. attributes intended for HTML interpolation. When trying to persist a model,
  1924. failed requests will now trigger an <tt>"error"</tt> event. The
  1925. ubiquitous <tt>options</tt> argument is now passed as the final argument
  1926. to all <tt>"change"</tt> events.
  1927. </p>
  1928. <p>
  1929. <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
  1930. Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
  1931. overridden on a per-model, or per-collection basis. Fixed recursion error
  1932. when calling <tt>save</tt> with no changed attributes, within a
  1933. <tt>"change"</tt> event.
  1934. </p>
  1935. <p>
  1936. <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
  1937. All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
  1938. model, so that views can listen for them without having to know about the
  1939. collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
  1940. <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
  1941. Backbone routes are now able to load empty URL fragments.
  1942. </p>
  1943. <p>
  1944. <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
  1945. Backbone now has <a href="#Controller">Controllers</a> and
  1946. <a href="#History">History</a>, for doing client-side routing based on
  1947. URL fragments.
  1948. Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
  1949. do <tt>PUT</tt> and <tt>DELETE</tt>.
  1950. Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
  1951. encoded requests.
  1952. Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
  1953. from a model.
  1954. All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
  1955. </p>
  1956. <p>
  1957. <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
  1958. Instead of requiring server responses to be namespaced under a <tt>model</tt>
  1959. key, now you can define your own <a href="#Model-parse">parse</a> method
  1960. to convert responses into attributes for Models and Collections.
  1961. The old <tt>handleEvents</tt> function is now named
  1962. <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
  1963. called as part of the View's constructor.
  1964. Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
  1965. Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
  1966. </p>
  1967. <p>
  1968. <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
  1969. Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
  1970. attributes of single model from the server.
  1971. An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
  1972. as an option, which will be invoked if validation fails, overriding the
  1973. <tt>"error"</tt> event.
  1974. You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
  1975. methods by setting <tt>Backbone.emulateHTTP = true</tt>.
  1976. Existing Model and Collection data is no longer sent up unnecessarily with
  1977. <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
  1978. Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
  1979. </p>
  1980. <p>
  1981. <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
  1982. Added a convention for <tt>initialize</tt> functions to be called
  1983. upon instance construction, if defined. Documentation tweaks.
  1984. </p>
  1985. <p>
  1986. <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
  1987. Initial Backbone release.
  1988. </p>
  1989. <p>
  1990. <br />
  1991. <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
  1992. <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
  1993. </a>
  1994. </p>
  1995. </div>
  1996. <script src="test/vendor/underscore-1.1.5.js"></script>
  1997. <script src="test/vendor/jquery-1.5.js"></script>
  1998. <script src="test/vendor/json2.js"></script>
  1999. <script src="backbone.js"></script>
  2000. <script>
  2001. // Set up the "play" buttons for each runnable code example.
  2002. $(function() {
  2003. $('.runnable').each(function() {
  2004. var code = this;
  2005. var button = $('<div class="run" title="Run"></div>');
  2006. $(button).insertBefore(code).bind('click', function(){
  2007. eval($(code).text());
  2008. });
  2009. });
  2010. });
  2011. </script>
  2012. </body>
  2013. </html>