PageRenderTime 62ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/index.html

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