PageRenderTime 75ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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