PageRenderTime 119ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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