PageRenderTime 56ms CodeModel.GetById 7ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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