PageRenderTime 70ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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