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

/index.html

https://github.com/jcteague/backbone
HTML | 3667 lines | 3177 code | 490 blank | 0 comment | 0 complexity | 1752e03d6946d58868d3999a0886457d 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. <link rel="icon" href="docs/images/favicon.ico" />
  7. <title>Backbone.js</title>
  8. <style>
  9. body {
  10. font-size: 14px;
  11. line-height: 22px;
  12. font-family: Helvetica Neue, Helvetica, Arial;
  13. background: #f4f4f4 url(docs/images/background.png);
  14. }
  15. .interface {
  16. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  17. }
  18. div#sidebar {
  19. background: #fff;
  20. position: fixed;
  21. top: 0; left: 0; bottom: 0;
  22. width: 200px;
  23. overflow-y: auto;
  24. overflow-x: hidden;
  25. padding: 15px 0 30px 30px;
  26. border-right: 1px solid #bbb;
  27. box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  28. }
  29. a.toc_title, a.toc_title:visited {
  30. display: block;
  31. color: black;
  32. font-weight: bold;
  33. margin-top: 15px;
  34. }
  35. a.toc_title:hover {
  36. text-decoration: underline;
  37. }
  38. #sidebar .version {
  39. font-size: 10px;
  40. font-weight: normal;
  41. }
  42. ul.toc_section {
  43. font-size: 11px;
  44. line-height: 14px;
  45. margin: 5px 0 0 0;
  46. padding-left: 0px;
  47. list-style-type: none;
  48. font-family: Lucida Grande;
  49. }
  50. .toc_section li {
  51. cursor: pointer;
  52. margin: 0 0 3px 0;
  53. }
  54. .toc_section li a {
  55. text-decoration: none;
  56. color: black;
  57. }
  58. .toc_section li a:hover {
  59. text-decoration: underline;
  60. }
  61. div.container {
  62. position: relative;
  63. width: 550px;
  64. margin: 40px 0 50px 260px;
  65. }
  66. div.run {
  67. position: absolute;
  68. right: 15px;
  69. width: 26px; height: 18px;
  70. background: url('docs/images/arrows.png') no-repeat -26px 0;
  71. }
  72. div.run:active {
  73. background-position: -51px 0;
  74. }
  75. p, div.container ul {
  76. margin: 25px 0;
  77. width: 550px;
  78. }
  79. p.warning {
  80. font-size: 12px;
  81. line-height: 18px;
  82. font-style: italic;
  83. }
  84. div.container ul {
  85. list-style: circle;
  86. padding-left: 15px;
  87. font-size: 13px;
  88. line-height: 18px;
  89. }
  90. div.container ul li {
  91. margin-bottom: 10px;
  92. }
  93. div.container ul.small {
  94. font-size: 12px;
  95. }
  96. a, a:visited {
  97. color: #444;
  98. }
  99. a:active, a:hover {
  100. color: #000;
  101. }
  102. a.punch {
  103. display: inline-block;
  104. background: #4162a8;
  105. border-top: 1px solid #38538c;
  106. border-right: 1px solid #1f2d4d;
  107. border-bottom: 1px solid #151e33;
  108. border-left: 1px solid #1f2d4d;
  109. -webkit-border-radius: 4px;
  110. -moz-border-radius: 4px;
  111. -ms-border-radius: 4px;
  112. -o-border-radius: 4px;
  113. border-radius: 4px;
  114. -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  115. -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  116. -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  117. -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  118. box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  119. color: #fff;
  120. font: bold 14px "helvetica neue", helvetica, arial, sans-serif;
  121. line-height: 1;
  122. margin-bottom: 15px;
  123. padding: 8px 0 10px 0;
  124. text-align: center;
  125. text-shadow: 0px -1px 1px #1e2d4d;
  126. text-decoration: none;
  127. width: 225px;
  128. -webkit-background-clip: padding-box; }
  129. a.punch:hover {
  130. -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  131. -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  132. -ms-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  133. -o-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  134. box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  135. cursor: pointer; }
  136. a.punch:active {
  137. -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  138. -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  139. -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  140. -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  141. box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  142. margin-top: 5px; margin-bottom: 10px }
  143. a img {
  144. border: 0;
  145. }
  146. h1, h2, h3, h4, h5, h6 {
  147. padding-top: 20px;
  148. }
  149. h2 {
  150. font-size: 22px;
  151. }
  152. b.header {
  153. font-size: 18px;
  154. line-height: 35px;
  155. }
  156. span.alias {
  157. font-size: 14px;
  158. font-style: italic;
  159. margin-left: 20px;
  160. }
  161. table {
  162. margin: 15px 0 0; padding: 0;
  163. }
  164. tr, td {
  165. margin: 0; padding: 0;
  166. }
  167. td {
  168. padding: 0px 15px 5px 0;
  169. }
  170. code, pre, tt {
  171. font-family: Monaco, Consolas, "Lucida Console", monospace;
  172. font-size: 12px;
  173. line-height: 18px;
  174. font-style: normal;
  175. }
  176. tt {
  177. padding: 0px 3px;
  178. background: #fff;
  179. border: 1px solid #ddd;
  180. zoom: 1;
  181. }
  182. code {
  183. margin-left: 20px;
  184. }
  185. pre {
  186. font-size: 12px;
  187. padding: 2px 0 2px 15px;
  188. border: 4px solid #bbb; border-top: 0; border-bottom: 0;
  189. margin: 0px 0 25px;
  190. }
  191. img.example_image {
  192. margin: 0px auto;
  193. }
  194. </style>
  195. </head>
  196. <body>
  197. <div id="sidebar" class="interface">
  198. <a class="toc_title" href="#">
  199. Backbone.js <span class="version">(0.9.2)</span>
  200. </a>
  201. <ul class="toc_section">
  202. <li>&raquo; <a href="http://github.com/documentcloud/backbone">GitHub Repository</a></li>
  203. <li>&raquo; <a href="docs/backbone.html">Annotated Source</a></li>
  204. </ul>
  205. <a class="toc_title" href="#introduction">
  206. Introduction
  207. </a>
  208. <a class="toc_title" href="#upgrading">
  209. Upgrading
  210. </a>
  211. <a class="toc_title" href="#Events">
  212. Events
  213. </a>
  214. <ul class="toc_section">
  215. <li> <a href="#Events-on">on</a></li>
  216. <li> <a href="#Events-off">off</a></li>
  217. <li> <a href="#Events-trigger">trigger</a></li>
  218. </ul>
  219. <a class="toc_title" href="#Model">
  220. Model
  221. </a>
  222. <ul class="toc_section">
  223. <li> <a href="#Model-extend">extend</a></li>
  224. <li> <a href="#Model-constructor">constructor / initialize</a></li>
  225. <li> <a href="#Model-get">get</a></li>
  226. <li> <a href="#Model-set">set</a></li>
  227. <li> <a href="#Model-escape">escape</a></li>
  228. <li> <a href="#Model-has">has</a></li>
  229. <li> <a href="#Model-unset">unset</a></li>
  230. <li> <a href="#Model-clear">clear</a></li>
  231. <li> <a href="#Model-id">id</a></li>
  232. <li> <a href="#Model-idAttribute">idAttribute</a></li>
  233. <li> <a href="#Model-cid">cid</a></li>
  234. <li> <a href="#Model-attributes">attributes</a></li>
  235. <li> <a href="#Model-changed">changed</a></li>
  236. <li> <a href="#Model-defaults">defaults</a></li>
  237. <li> <a href="#Model-toJSON">toJSON</a></li>
  238. <li> <a href="#Model-fetch">fetch</a></li>
  239. <li> <a href="#Model-save">save</a></li>
  240. <li> <a href="#Model-destroy">destroy</a></li>
  241. <li> <a href="#Model-validate">validate</a></li>
  242. <li> <a href="#Model-isValid">isValid</a></li>
  243. <li> <a href="#Model-url">url</a></li>
  244. <li> <a href="#Model-urlRoot">urlRoot</a></li>
  245. <li> <a href="#Model-parse">parse</a></li>
  246. <li> <a href="#Model-clone">clone</a></li>
  247. <li> <a href="#Model-isNew">isNew</a></li>
  248. <li> <a href="#Model-change">change</a></li>
  249. <li> <a href="#Model-hasChanged">hasChanged</a></li>
  250. <li> <a href="#Model-changedAttributes">changedAttributes</a></li>
  251. <li> <a href="#Model-previous">previous</a></li>
  252. <li> <a href="#Model-previousAttributes">previousAttributes</a></li>
  253. </ul>
  254. <a class="toc_title" href="#Collection">
  255. Collection
  256. </a>
  257. <ul class="toc_section">
  258. <li> <a href="#Collection-extend">extend</a></li>
  259. <li> <a href="#Collection-model">model</a></li>
  260. <li> <a href="#Collection-constructor">constructor / initialize</a></li>
  261. <li> <a href="#Collection-models">models</a></li>
  262. <li> <a href="#Collection-toJSON">toJSON</a></li>
  263. <li> <a href="#Collection-Underscore-Methods"><b>Underscore Methods (28)</b></a></li>
  264. <li> <a href="#Collection-add">add</a></li>
  265. <li> <a href="#Collection-remove">remove</a></li>
  266. <li> <a href="#Collection-get">get</a></li>
  267. <li> <a href="#Collection-getByCid">getByCid</a></li>
  268. <li> <a href="#Collection-at">at</a></li>
  269. <li> <a href="#Collection-push">push</a></li>
  270. <li> <a href="#Collection-pop">pop</a></li>
  271. <li> <a href="#Collection-unshift">unshift</a></li>
  272. <li> <a href="#Collection-shift">shift</a></li>
  273. <li> <a href="#Collection-length">length</a></li>
  274. <li> <a href="#Collection-comparator">comparator</a></li>
  275. <li> <a href="#Collection-sort">sort</a></li>
  276. <li> <a href="#Collection-pluck">pluck</a></li>
  277. <li> <a href="#Collection-where">where</a></li>
  278. <li> <a href="#Collection-url">url</a></li>
  279. <li> <a href="#Collection-parse">parse</a></li>
  280. <li> <a href="#Collection-fetch">fetch</a></li>
  281. <li> <a href="#Collection-reset">reset</a></li>
  282. <li> <a href="#Collection-create">create</a></li>
  283. </ul>
  284. <a class="toc_title" href="#Router">
  285. Router
  286. </a>
  287. <ul class="toc_section">
  288. <li> <a href="#Router-extend">extend</a></li>
  289. <li> <a href="#Router-routes">routes</a></li>
  290. <li> <a href="#Router-constructor">constructor / initialize</a></li>
  291. <li> <a href="#Router-route">route</a></li>
  292. <li> <a href="#Router-navigate">navigate</a></li>
  293. </ul>
  294. <a class="toc_title" href="#History">
  295. History
  296. </a>
  297. <ul class="toc_section">
  298. <li> <a href="#History-start">start</a></li>
  299. </ul>
  300. <a class="toc_title" href="#Sync">
  301. Sync
  302. </a>
  303. <ul class="toc_section">
  304. <li> <a href="#Sync">Backbone.sync</a></li>
  305. <li> <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
  306. <li> <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
  307. </ul>
  308. <a class="toc_title" href="#View">
  309. View
  310. </a>
  311. <ul class="toc_section">
  312. <li> <a href="#View-extend">extend</a></li>
  313. <li> <a href="#View-constructor">constructor / initialize</a></li>
  314. <li> <a href="#View-el">el</a></li>
  315. <li> <a href="#View-$el">$el</a></li>
  316. <li> <a href="#View-setElement">setElement</a></li>
  317. <li> <a href="#View-attributes">attributes</a></li>
  318. <li> <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
  319. <li> <a href="#View-render">render</a></li>
  320. <li> <a href="#View-remove">remove</a></li>
  321. <li> <a href="#View-make">make</a></li>
  322. <li> <a href="#View-delegateEvents">delegateEvents</a></li>
  323. <li> <a href="#View-undelegateEvents">undelegateEvents</a></li>
  324. </ul>
  325. <a class="toc_title" href="#Utility">
  326. Utility
  327. </a>
  328. <ul class="toc_section">
  329. <li> <a href="#Utility-noConflict">noConflict</a></li>
  330. <li> <a href="#Utility-setDomLibrary">setDomLibrary</a></li>
  331. </ul>
  332. <a class="toc_title" href="#examples">
  333. Examples
  334. </a>
  335. <ul class="toc_section">
  336. <li> <a href="#examples-todos">Todos</a></li>
  337. <li> <a href="#examples-documentcloud">DocumentCloud</a></li>
  338. <li> <a href="#examples-linkedin">LinkedIn Mobile</a></li>
  339. <li> <a href="#examples-flow">Flow</a></li>
  340. <li> <a href="#examples-audiovroom">AudioVroom</a></li>
  341. <li> <a href="#examples-foursquare">Foursquare</a></li>
  342. <li> <a href="#examples-wunderkit">Wunderkit</a></li>
  343. <li> <a href="#examples-khan-academy">Khan Academy</a></li>
  344. <li> <a href="#examples-do">Do</a></li>
  345. <li> <a href="#examples-posterous">Posterous Spaces</a></li>
  346. <li> <a href="#examples-groupon">Groupon Now!</a></li>
  347. <li> <a href="#examples-basecamp">Basecamp Mobile</a></li>
  348. <li> <a href="#examples-slavery-footprint">Slavery Footprint</a></li>
  349. <li> <a href="#examples-stripe">Stripe</a></li>
  350. <li> <a href="#examples-airbnb">Airbnb Mobile</a></li>
  351. <li> <a href="#examples-diaspora">Diaspora</a></li>
  352. <li> <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
  353. <li> <a href="#examples-pandora">Pandora</a></li>
  354. <li> <a href="#examples-code-school">Code School</a></li>
  355. <li> <a href="#examples-cloudapp">CloudApp</a></li>
  356. <li> <a href="#examples-seatgeek">SeatGeek</a></li>
  357. <li> <a href="#examples-grove">Grove.io</a></li>
  358. <li> <a href="#examples-kicksend">Kicksend</a></li>
  359. <li> <a href="#examples-shortmail">Shortmail</a></li>
  360. <li> <a href="#examples-battlefield">Battlefield Play4Free</a></li>
  361. <li> <a href="#examples-salon">Salon.io</a></li>
  362. <li> <a href="#examples-tilemill">TileMill</a></li>
  363. <li> <a href="#examples-blossom">Blossom</a></li>
  364. <li> <a href="#examples-animoto">Animoto</a></li>
  365. <li> <a href="#examples-chaincal">ChainCal</a></li>
  366. <li> <a href="#examples-attictv">AtticTV</a></li>
  367. <li> <a href="#examples-decide">Decide</a></li>
  368. <li> <a href="#examples-editd">EDITD</a></li>
  369. <li> <a href="#examples-trello">Trello</a></li>
  370. <li> <a href="#examples-ducksboard">Ducksboard</a></li>
  371. <li> <a href="#examples-quietwrite">QuietWrite</a></li>
  372. <li> <a href="#examples-tzigla">Tzigla</a></li>
  373. </ul>
  374. <a class="toc_title" href="#faq">
  375. F.A.Q.
  376. </a>
  377. <ul class="toc_section">
  378. <li> <a href="#FAQ-events">Catalog of Events</a></li>
  379. <li> <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
  380. <li> <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
  381. <li> <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
  382. <li> <a href="#FAQ-extending">Extending Backbone</a></li>
  383. <li> <a href="#FAQ-mvc">Traditional MVC</a></li>
  384. <li> <a href="#FAQ-this">Binding "this"</a></li>
  385. <li> <a href="#FAQ-rails">Working with Rails</a></li>
  386. </ul>
  387. <a class="toc_title" href="#changelog">
  388. Change Log
  389. </a>
  390. </div>
  391. <div class="container">
  392. <p>
  393. <img style="width: 451px; height: 80px;" src="docs/images/backbone.png" alt="Backbone.js" />
  394. </p>
  395. <p>
  396. Backbone.js gives structure to web applications
  397. by providing <b>models</b> with key-value binding and custom events,
  398. <b>collections</b> with a rich API of enumerable functions,
  399. <b>views</b> with declarative event handling, and connects it all to your
  400. existing API over a RESTful JSON interface.
  401. </p>
  402. <p>
  403. The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
  404. and the <a href="docs/backbone.html">annotated source code</a> is available,
  405. as well as an online <a href="test/test.html">test suite</a>,
  406. an <a href="examples/todos/index.html">example application</a>,
  407. a <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>
  408. and a <a href="#examples">long list of real-world projects</a> that use Backbone.
  409. Backbone is available for use under the <a href="http://github.com/documentcloud/backbone/blob/master/LICENSE">MIT software license</a>.
  410. </p>
  411. <p>
  412. You can report bugs and discuss features on the
  413. <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
  414. on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
  415. <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
  416. add pages to the <a href="https://github.com/documentcloud/backbone/wiki">wiki</a>
  417. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  418. </p>
  419. <p>
  420. <i>
  421. Backbone is an open-source component of
  422. <a href="http://documentcloud.org/">DocumentCloud</a>.
  423. </i>
  424. </p>
  425. <h2 id="downloads">
  426. Downloads &amp; Dependencies
  427. <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
  428. </h2>
  429. <table>
  430. <tr>
  431. <td><a class="punch" href="backbone.js">Development Version (0.9.2)</a></td>
  432. <td><i>52kb, Full source, lots of comments</i></td>
  433. </tr>
  434. <tr>
  435. <td><a class="punch" href="backbone-min.js">Production Version (0.9.2)</a></td>
  436. <td><i>5.6kb, Packed and gzipped</i></td>
  437. </tr>
  438. </table>
  439. <p>
  440. Backbone's only hard dependency is
  441. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> <small>( > 1.3.1)</small>.
  442. For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
  443. and DOM manipulation with <a href="#View">Backbone.View</a>, include
  444. <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
  445. <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or
  446. <a href="http://zeptojs.com/">Zepto</a>.
  447. </p>
  448. <h2 id="introduction">Introduction</h2>
  449. <p>
  450. When working on a web application that involves a lot of JavaScript, one
  451. of the first things you learn is to stop tying your data to the DOM. It's all
  452. too easy to create JavaScript applications that end up as tangled piles of
  453. jQuery selectors and callbacks, all trying frantically to keep data in
  454. sync between the HTML UI, your JavaScript logic, and the database on your
  455. server. For rich client-side applications, a more structured approach
  456. is often helpful.
  457. </p>
  458. <p>
  459. With Backbone, you represent your data as
  460. <a href="#Model">Models</a>, which can be created, validated, destroyed,
  461. and saved to the server. Whenever a UI action causes an attribute of
  462. a model to change, the model triggers a <i>"change"</i> event; all
  463. the <a href="#View">Views</a> that display the model's state can be notified of the
  464. change, so that they are able to respond accordingly, re-rendering themselves with
  465. the new information. In a finished Backbone app, you don't have to write the glue
  466. code that looks into the DOM to find an element with a specific <i>id</i>,
  467. and update the HTML manually
  468. &mdash; when the model changes, the views simply update themselves.
  469. </p>
  470. <p>
  471. If you're new here, and aren't yet quite sure what Backbone is for, start by
  472. browsing the <a href="#examples">list of Backbone-based projects</a>.
  473. </p>
  474. <p>
  475. Many of the examples that follow are runnable. Click the <i>play</i> button
  476. to execute them.
  477. </p>
  478. <h2 id="upgrading">Upgrading to 0.9</h2>
  479. <p>
  480. Backbone's <b>0.9</b> series should be considered as a release candidate
  481. for an upcoming <b>1.0</b>. Some APIs have changed, and while there is a
  482. <a href="#changelog">change log</a> available, and many new features to
  483. take advantage of, there are a few specific changes where you'll need
  484. to take care:
  485. </p>
  486. <ul>
  487. <li>
  488. If you've ever manually set <tt>this.el</tt> in a Backbone View to be a
  489. particular DOM element, you'll want to use
  490. <a href="#View-setElement">setElement</a> instead.
  491. </li>
  492. <li>
  493. Creating and destroying models is now optimistic. Pass <tt>{wait: true}</tt>
  494. if you need the previous behavior of waiting for the server to acknowledge
  495. success. You can now also pass <tt>{wait: true}</tt> to <a href="#Model-save">save</a> calls.
  496. </li>
  497. <li>
  498. If you have been writing a fair amount of <tt>$(view.el)</tt>, there's now
  499. a cached reference for that jQuery object: <a href="#View-$el">$el</a>.
  500. </li>
  501. <li>
  502. If you're upgrading, make sure you also upgrade your version of Underscore.js
  503. to the latest &mdash; 1.3.1 or greater.
  504. </li>
  505. <li>
  506. <tt>model.set</tt> will no longer trigger change events when setting a value
  507. with <tt>{silent: true}</tt> then setting it back to its original value.
  508. Similarly, after changing an attribute silently, that <tt>change:attribute</tt>
  509. event <i>will</i> fire during the next change.
  510. </li>
  511. <li>
  512. Since <tt>view.$(selector)</tt> is now equivalent to <tt>view.$el.find(selector)</tt>
  513. rather than <tt>$(selector, view.el)</tt> it can no longer be used when
  514. <tt>selector</tt> is an HTML string or DOM element.
  515. </li>
  516. </ul>
  517. <h2 id="Events">Backbone.Events</h2>
  518. <p>
  519. <b>Events</b> is a module that can be mixed in to any object, giving the
  520. object the ability to bind and trigger custom named events. Events do not
  521. have to be declared before they are bound, and may take passed arguments.
  522. For example:
  523. </p>
  524. <pre class="runnable">
  525. var object = {};
  526. _.extend(object, Backbone.Events);
  527. object.on("alert", function(msg) {
  528. alert("Triggered " + msg);
  529. });
  530. object.trigger("alert", "an event");
  531. </pre>
  532. <p>
  533. For example, to make a handy event dispatcher that can coordinate events
  534. among different areas of your application: <tt>var dispatcher = _.clone(Backbone.Events)</tt>
  535. </p>
  536. <p id="Events-on">
  537. <b class="header">on</b><code>object.on(event, callback, [context])</code><span class="alias">Alias: bind</span>
  538. <br />
  539. Bind a <b>callback</b> function to an object. The callback will be invoked
  540. whenever the <b>event</b> is fired.
  541. If you have a large number of different events on a page, the convention is to use colons to
  542. namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>.
  543. The event string may also be a space-delimited list of several events...
  544. </p>
  545. <pre>
  546. book.on("change:title change:author", ...);
  547. </pre>
  548. <p>
  549. To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
  550. pass the optional third argument: <tt>model.on('change', this.render, this)</tt>
  551. </p>
  552. <p>
  553. Callbacks bound to the special
  554. <tt>"all"</tt> event will be triggered when any event occurs, and are passed
  555. the name of the event as the first argument. For example, to proxy all events
  556. from one object to another:
  557. </p>
  558. <pre>
  559. proxy.on("all", function(eventName) {
  560. object.trigger(eventName);
  561. });
  562. </pre>
  563. <p id="Events-off">
  564. <b class="header">off</b><code>object.off([event], [callback], [context])</code><span class="alias">Alias: unbind</span>
  565. <br />
  566. Remove a previously-bound <b>callback</b> function from an object. If no
  567. <b>context</b> is specified, all of the versions of the callback with
  568. different contexts will be removed. If no
  569. callback is specified, all callbacks for the <b>event</b> will be
  570. removed. If no event is specified, <i>all</i> event callbacks on the object
  571. will be removed.
  572. </p>
  573. <pre>
  574. // Removes just the `onChange` callback.
  575. object.off("change", onChange);
  576. // Removes all "change" callbacks.
  577. object.off("change");
  578. // Removes the `onChange` callback for all events.
  579. object.off(null, onChange);
  580. // Removes all callbacks for `context` for all events.
  581. object.off(null, null, context);
  582. // Removes all callbacks on `object`.
  583. object.off();
  584. </pre>
  585. <p id="Events-trigger">
  586. <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
  587. <br />
  588. Trigger callbacks for the given <b>event</b>, or space-delimited list of events.
  589. Subsequent arguments to <b>trigger</b> will be passed along to the
  590. event callbacks.
  591. </p>
  592. <h2 id="Model">Backbone.Model</h2>
  593. <p>
  594. <b>Models</b> are the heart of any JavaScript application, containing
  595. the interactive data as well as a large part of the logic surrounding it:
  596. conversions, validations, computed properties, and access control. You
  597. extend <b>Backbone.Model</b> with your domain-specific methods, and
  598. <b>Model</b> provides a basic set of functionality for managing changes.
  599. </p>
  600. <p>
  601. The following is a contrived example, but it demonstrates defining a model
  602. with a custom method, setting an attribute, and firing an event keyed
  603. to changes in that specific attribute.
  604. After running this code once, <tt>sidebar</tt> will be
  605. available in your browser's console, so you can play around with it.
  606. </p>
  607. <pre class="runnable">
  608. var Sidebar = Backbone.Model.extend({
  609. promptColor: function() {
  610. var cssColor = prompt("Please enter a CSS color:");
  611. this.set({color: cssColor});
  612. }
  613. });
  614. window.sidebar = new Sidebar;
  615. sidebar.on('change:color', function(model, color) {
  616. $('#sidebar').css({background: color});
  617. });
  618. sidebar.set({color: 'white'});
  619. sidebar.promptColor();
  620. </pre>
  621. <p id="Model-extend">
  622. <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
  623. <br />
  624. To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
  625. and provide instance <b>properties</b>, as well as optional
  626. <b>classProperties</b> to be attached directly to the constructor function.
  627. </p>
  628. <p>
  629. <b>extend</b> correctly sets up the prototype chain, so subclasses created
  630. with <b>extend</b> can be further extended and subclassed as far as you like.
  631. </p>
  632. <pre>
  633. var Note = Backbone.Model.extend({
  634. initialize: function() { ... },
  635. author: function() { ... },
  636. coordinates: function() { ... },
  637. allowedToEdit: function(account) {
  638. return true;
  639. }
  640. });
  641. var PrivateNote = Note.extend({
  642. allowedToEdit: function(account) {
  643. return account.owns(this);
  644. }
  645. });
  646. </pre>
  647. <p class="warning">
  648. Brief aside on <tt>super</tt>: JavaScript does not provide
  649. a simple way to call super &mdash; the function of the same name defined
  650. higher on the prototype chain. If you override a core function like
  651. <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
  652. parent object's implementation, you'll have to explicitly call it, along these lines:
  653. </p>
  654. <pre>
  655. var Note = Backbone.Model.extend({
  656. set: function(attributes, options) {
  657. Backbone.Model.prototype.set.call(this, attributes, options);
  658. ...
  659. }
  660. });
  661. </pre>
  662. <p id="Model-constructor">
  663. <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
  664. <br />
  665. When creating an instance of a model, you can pass in the initial values
  666. of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
  667. model. If you define an <b>initialize</b> function, it will be invoked when
  668. the model is created.
  669. </p>
  670. <pre>
  671. new Book({
  672. title: "One Thousand and One Nights",
  673. author: "Scheherazade"
  674. });
  675. </pre>
  676. <p>
  677. In rare cases, if you're looking to get fancy,
  678. you may want to override <b>constructor</b>, which allows
  679. you to replace the actual constructor function for your model.
  680. </p>
  681. <p id="Model-get">
  682. <b class="header">get</b><code>model.get(attribute)</code>
  683. <br />
  684. Get the current value of an attribute from the model. For example:
  685. <tt>note.get("title")</tt>
  686. </p>
  687. <p id="Model-set">
  688. <b class="header">set</b><code>model.set(attributes, [options])</code>
  689. <br />
  690. Set a hash of attributes (one or many) on the model. If any of the attributes
  691. change the models state, a <tt>"change"</tt> event will be triggered, unless
  692. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  693. attributes are also triggered, and you can bind to those as well, for example:
  694. <tt>change:title</tt>, and <tt>change:content</tt>. You may also pass
  695. individual keys and values.
  696. </p>
  697. <pre>
  698. note.set({title: "March 20", content: "In his eyes she eclipses..."});
  699. book.set("title", "A Scandal in Bohemia");
  700. </pre>
  701. <p>
  702. If the model has a <a href="#Model-validate">validate</a> method,
  703. it will be validated before the attributes are set, no changes will
  704. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  705. Otherwise, <b>set</b> returns a reference to the model.
  706. You may also pass an <tt>error</tt>
  707. callback in the options, which will be invoked instead of triggering an
  708. <tt>"error"</tt> event, should validation fail.
  709. If <tt>{silent: true}</tt> is passed as an option, the validation is deferred
  710. until the next change.
  711. </p>
  712. <p id="Model-escape">
  713. <b class="header">escape</b><code>model.escape(attribute)</code>
  714. <br />
  715. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  716. of a model's attribute. If you're interpolating data from the model into
  717. HTML, using <b>escape</b> to retrieve attributes will prevent
  718. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  719. </p>
  720. <pre class="runnable">
  721. var hacker = new Backbone.Model({
  722. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  723. });
  724. alert(hacker.escape('name'));
  725. </pre>
  726. <p id="Model-has">
  727. <b class="header">has</b><code>model.has(attribute)</code>
  728. <br />
  729. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  730. value.
  731. </p>
  732. <pre>
  733. if (note.has("title")) {
  734. ...
  735. }
  736. </pre>
  737. <p id="Model-unset">
  738. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  739. <br />
  740. Remove an attribute by deleting it from the internal attributes hash.
  741. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  742. </p>
  743. <p id="Model-clear">
  744. <b class="header">clear</b><code>model.clear([options])</code>
  745. <br />
  746. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  747. <tt>silent</tt> is passed as an option.
  748. </p>
  749. <p id="Model-id">
  750. <b class="header">id</b><code>model.id</code>
  751. <br />
  752. A special property of models, the <b>id</b> is an arbitrary string
  753. (integer id or UUID). If you set the <b>id</b> in the
  754. attributes hash, it will be copied onto the model as a direct property.
  755. Models can be retrieved by id from collections, and the id is used to generate
  756. model URLs by default.
  757. </p>
  758. <p id="Model-idAttribute">
  759. <b class="header">idAttribute</b><code>model.idAttribute</code>
  760. <br />
  761. A model's unique identifier is stored under the <tt>id</tt> attribute.
  762. If you're directly communicating with a backend (CouchDB, MongoDB) that uses
  763. a different unique key, you may set a Model's <tt>idAttribute</tt> to
  764. transparently map from that key to <tt>id</tt>.
  765. <pre class="runnable">
  766. var Meal = Backbone.Model.extend({
  767. idAttribute: "_id"
  768. });
  769. var cake = new Meal({ _id: 1, name: "Cake" });
  770. alert("Cake id: " + cake.id);
  771. </pre>
  772. </p>
  773. <p id="Model-cid">
  774. <b class="header">cid</b><code>model.cid</code>
  775. <br />
  776. A special property of models, the <b>cid</b> or client id is a unique identifier
  777. automatically assigned to all models when they're first created. Client ids
  778. are handy when the model has not yet been saved to the server, and does not
  779. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  780. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  781. </p>
  782. <p id="Model-attributes">
  783. <b class="header">attributes</b><code>model.attributes</code>
  784. <br />
  785. The <b>attributes</b> property is the internal hash containing the model's
  786. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  787. them directly. If you'd like to retrieve and munge a copy of the model's
  788. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  789. </p>
  790. <p id="Model-changed">
  791. <b class="header">changed</b><code>model.changed</code>
  792. <br />
  793. The <b>changed</b> property is the internal hash containing all the attributes
  794. that have changed since the last <tt>"change"</tt> event was triggered.
  795. Please do not update <b>changed</b> directly. Its state is maintained internally
  796. by <a href="#Model-set">set</a> and <a href="#Model-change">change</a>.
  797. A copy of <b>changed</b> can be acquired from
  798. <a href="#Model-changedAttributes">changedAttributes</a>.
  799. </p>
  800. <p id="Model-defaults">
  801. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  802. <br />
  803. The <b>defaults</b> hash (or function) can be used to specify the default
  804. attributes for your model. When creating an instance of the model,
  805. any unspecified attributes will be set to their default value.
  806. </p>
  807. <pre class="runnable">
  808. var Meal = Backbone.Model.extend({
  809. defaults: {
  810. "appetizer": "caesar salad",
  811. "entree": "ravioli",
  812. "dessert": "cheesecake"
  813. }
  814. });
  815. alert("Dessert will be " + (new Meal).get('dessert'));
  816. </pre>
  817. <p class="warning">
  818. Remember that in JavaScript, objects are passed by reference, so if you
  819. include an object as a default value, it will be shared among all instances.
  820. </p>
  821. <p id="Model-toJSON">
  822. <b class="header">toJSON</b><code>model.toJSON()</code>
  823. <br />
  824. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  825. This can be used for persistence, serialization, or for augmentation before
  826. being handed off to a view. The name of this method is a bit confusing, as
  827. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  828. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  829. </p>
  830. <pre class="runnable">
  831. var artist = new Backbone.Model({
  832. firstName: "Wassily",
  833. lastName: "Kandinsky"
  834. });
  835. artist.set({birthday: "December 16, 1866"});
  836. alert(JSON.stringify(artist));
  837. </pre>
  838. <p id="Model-fetch">
  839. <b class="header">fetch</b><code>model.fetch([options])</code>
  840. <br />
  841. Resets the model's state from the server by delegating to
  842. <a href="#Sync">Backbone.sync</a>. Returns a
  843. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>.
  844. Useful if the model has never
  845. been populated with data, or if you'd like to ensure that you have the
  846. latest server state. A <tt>"change"</tt> event will be triggered if the
  847. server's state differs from the current attributes. Accepts
  848. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  849. are passed <tt>(model, response)</tt> as arguments.
  850. </p>
  851. <pre>
  852. // Poll every 10 seconds to keep the channel model up-to-date.
  853. setInterval(function() {
  854. channel.fetch();
  855. }, 10000);
  856. </pre>
  857. <p id="Model-save">
  858. <b class="header">save</b><code>model.save([attributes], [options])</code>
  859. <br />
  860. Save a model to your database (or alternative persistence layer),
  861. by delegating to <a href="#Sync">Backbone.sync</a>. Returns a
  862. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> if
  863. validation is successful and <tt>false</tt> otherwise. The <b>attributes</b>
  864. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  865. you'd like to change &mdash; keys that aren't mentioned won't be altered &mdash; but,
  866. a <i>complete representation</i> of the resource will be sent to the server.
  867. As with <tt>set</tt>, you may pass individual keys and values instead of a hash.
  868. If the model has a <a href="#Model-validate">validate</a>
  869. method, and validation fails, the model will not be saved. If the model
  870. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  871. (HTTP <tt>POST</tt>), if the model already
  872. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  873. </p>
  874. <p>
  875. Calling <tt>save</tt> with new attributes will cause a <tt>"change"</tt>
  876. event immediately, and a <tt>"sync"</tt> event after the server has acknowledged
  877. the successful change. Pass <tt>{wait: true}</tt> if you'd like to wait
  878. for the server before setting the new attributes on the model.
  879. </p>
  880. <p>
  881. In the following example, notice how our overridden version
  882. of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
  883. the first time the model is saved and an <tt>"update"</tt>
  884. request the second time.
  885. </p>
  886. <pre class="runnable">
  887. Backbone.sync = function(method, model) {
  888. alert(method + ": " + JSON.stringify(model));
  889. model.id = 1;
  890. };
  891. var book = new Backbone.Model({
  892. title: "The Rough Riders",
  893. author: "Theodore Roosevelt"
  894. });
  895. book.save();
  896. book.save({author: "Teddy"});
  897. </pre>
  898. <p>
  899. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  900. options hash, which are passed <tt>(model, response)</tt> as arguments.
  901. The <tt>error</tt> callback will also be invoked if the model has a
  902. <tt>validate</tt> method, and validation fails. If a server-side
  903. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  904. an error response in text or JSON.
  905. </p>
  906. <pre>
  907. book.save("author", "F.D.R.", {error: function(){ ... }});
  908. </pre>
  909. <p id="Model-destroy">
  910. <b class="header">destroy</b><code>model.destroy([options])</code>
  911. <br />
  912. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  913. request to <a href="#Sync">Backbone.sync</a>. Returns a
  914. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> object, or
  915. <tt>false</tt> if the model <a href="#Model-isNew">isNew</a>. Accepts
  916. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  917. Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
  918. through any collections that contain it, and a <tt>"sync"</tt> event, after
  919. the server has successfully acknowledged the model's deletion. Pass
  920. <tt>{wait: true}</tt> if you'd like to wait for the server to respond
  921. before removing the model from the collection.
  922. </p>
  923. <pre>
  924. book.destroy({success: function(model, response) {
  925. ...
  926. }});
  927. </pre>
  928. <p id="Model-validate">
  929. <b class="header">validate</b><code>model.validate(attributes)</code>
  930. <br />
  931. This method is left undefined, and you're encouraged to override it with
  932. your custom validation logic, if you have any that can be performed
  933. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  934. <tt>save</tt>, and is passed the model attributes updated with the values
  935. from <tt>set</tt> or <tt>save</tt>.
  936. If the attributes are valid, don't return anything from <b>validate</b>;
  937. if they are invalid, return an error of your choosing. It
  938. can be as simple as a string error message to be displayed, or a complete
  939. error object that describes the error programmatically. If <b>validate</b>
  940. returns an error, <tt>set</tt> and <tt>save</tt> will not continue, and the
  941. model attributes will not be modified.
  942. Failed validations trigger an <tt>"error"</tt> event.
  943. </p>
  944. <pre class="runnable">
  945. var Chapter = Backbone.Model.extend({
  946. validate: function(attrs) {
  947. if (attrs.end < attrs.start) {
  948. return "can't end before it starts";
  949. }
  950. }
  951. });
  952. var one = new Chapter({
  953. title : "Chapter One: The Beginning"
  954. });
  955. one.on("error", function(model, error) {
  956. alert(model.get("title") + " " + error);
  957. });
  958. one.set({
  959. start: 15,
  960. end: 10
  961. });
  962. </pre>
  963. <p>
  964. <tt>"error"</tt> events are useful for providing coarse-grained error
  965. messages at the model or collection level, but if you have a specific view
  966. that can better handle the error, you may override and suppress the event
  967. by passing an <tt>error</tt> callback directly:
  968. </p>
  969. <pre>
  970. account.set({access: "unlimited"}, {
  971. error: function(model, error) {
  972. alert(error);
  973. }
  974. });
  975. </pre>
  976. <p id="Model-isValid">
  977. <b class="header">isValid</b><code>model.isValid()</code>
  978. <br />
  979. Models may enter an invalid state if you make changes to them silently
  980. ... useful when dealing with form input. Call <tt>model.isValid()</tt>
  981. to check if the model is currently in a valid state, according to your
  982. <tt>validate</tt> function.
  983. </p>
  984. <p id="Model-url">
  985. <b class="header">url</b><code>model.url()</code>
  986. <br />
  987. Returns the relative URL where the model's resource would be located on
  988. the server. If your models are located somewhere else, override this method
  989. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  990. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  991. </p>
  992. <p>
  993. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  994. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  995. property, if all models of this class share a common root URL.
  996. A model with an id of <tt>101</tt>, stored in a
  997. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  998. would have this URL: <tt>"/documents/7/notes/101"</tt>
  999. </p>
  1000. <p id="Model-urlRoot">
  1001. <b class="header">urlRoot</b><code>model.urlRoot or model.urlRoot()</code>
  1002. <br />
  1003. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  1004. to enable the default <a href="#Model-url">url</a> function to generate
  1005. URLs based on the model id. <tt>"/[urlRoot]/id"</tt><br />
  1006. Note that <tt>urlRoot</tt> may also be defined as a function.
  1007. </p>
  1008. <pre class="runnable">
  1009. var Book = Backbone.Model.extend({urlRoot : '/books'});
  1010. var solaris = new Book({id: "1083-lem-solaris"});
  1011. alert(solaris.url());
  1012. </pre>
  1013. <p id="Model-parse">
  1014. <b class="header">parse</b><code>model.parse(response)</code>
  1015. <br />
  1016. <b>parse</b> is called whenever a model's data is returned by the
  1017. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  1018. The function is passed the raw <tt>response</tt> object, and should return
  1019. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  1020. default implementation is a no-op, simply passing through the JSON response.
  1021. Override this if you need to work with a preexisting API, or better namespace
  1022. your responses.
  1023. </p>
  1024. <p>
  1025. If you're working with a Rails backend, you'll notice that Rails' default
  1026. <tt>to_json</tt> implementation includes a model's attributes under a
  1027. namespace. To disable this behavior for seamless Backbone integration, set:
  1028. </p>
  1029. <pre>
  1030. ActiveRecord::Base.include_root_in_json = false
  1031. </pre>
  1032. <p id="Model-clone">
  1033. <b class="header">clone</b><code>model.clone()</code>
  1034. <br />
  1035. Returns a new instance of the model with identical attributes.
  1036. </p>
  1037. <p id="Model-isNew">
  1038. <b class="header">isNew</b><code>model.isNew()</code>
  1039. <br />
  1040. Has this model been saved to the server yet? If the model does not yet have
  1041. an <tt>id</tt>, it is considered to be new.
  1042. </p>
  1043. <p id="Model-change">
  1044. <b class="header">change</b><code>model.change()</code>
  1045. <br />
  1046. Manually trigger the <tt>"change"</tt> event and a <tt>"change:attribute"</tt>
  1047. event for each attribute that has changed. If you've been passing
  1048. <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  1049. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  1050. when you're all finished.
  1051. </p>
  1052. <p id="Model-hasChanged">
  1053. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  1054. <br />
  1055. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  1056. is passed, returns <tt>true</tt> if that specific attribute has changed.
  1057. </p>
  1058. <p class="warning">
  1059. Note that this method, and the following change-related ones,
  1060. are only useful during the course of a <tt>"change"</tt> event.
  1061. </p>
  1062. <pre>
  1063. book.on("change", function() {
  1064. if (book.hasChanged("title")) {
  1065. ...
  1066. }
  1067. });
  1068. </pre>
  1069. <p id="Model-changedAttributes">
  1070. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  1071. <br />
  1072. Retrieve a hash of only the model's attributes that have changed. Optionally,
  1073. an external <b>attributes</b> hash can be passed in, returning
  1074. the attributes in that hash which differ from the model. This can be used
  1075. to figure out which portions of a view should be updated, or what calls
  1076. need to be made to sync the changes to the server.
  1077. </p>
  1078. <p id="Model-previous">
  1079. <b class="header">previous</b><code>model.previous(attribute)</code>
  1080. <br />
  1081. During a <tt>"change"</tt> event, this method can be used to get the
  1082. previous value of a changed attribute.
  1083. </p>
  1084. <pre class="runnable">
  1085. var bill = new Backbone.Model({
  1086. name: "Bill Smith"
  1087. });
  1088. bill.on("change:name", function(model, name) {
  1089. alert("Changed name from " + bill.previous("name") + " to " + name);
  1090. });
  1091. bill.set({name : "Bill Jones"});
  1092. </pre>
  1093. <p id="Model-previousAttributes">
  1094. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  1095. <br />
  1096. Return a copy of the model's previous attributes. Useful for getting a
  1097. diff between versions of a model, or getting back to a valid state after
  1098. an error occurs.
  1099. </p>
  1100. <h2 id="Collection">Backbone.Collection</h2>
  1101. <p>
  1102. Collections are ordered sets of models. You can bind <tt>"change"</tt> events
  1103. to be notified when any model in the collection has been modified,
  1104. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  1105. the collection from the server, and use a full suite of
  1106. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  1107. </p>
  1108. <p>
  1109. Any event that is triggered on a model in a collection will also be
  1110. triggered on the collection directly, for convenience.
  1111. This allows you to listen for changes to specific attributes in any
  1112. model in a collection, for example:
  1113. <tt>Documents.on("change:selected", ...)</tt>
  1114. </p>
  1115. <p id="Collection-extend">
  1116. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  1117. <br />
  1118. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  1119. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  1120. directly to the collection's constructor function.
  1121. </p>
  1122. <p id="Collection-model">
  1123. <b class="header">model</b><code>collection.model</code>
  1124. <br />
  1125. Override this property to specify the model class that the collection
  1126. contains. If defined, you can pass raw attributes objects (and arrays) to
  1127. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  1128. and <a href="#Collection-reset">reset</a>, and the attributes will be
  1129. converted into a model of the proper type.
  1130. </p>
  1131. <pre>
  1132. var Library = Backbone.Collection.extend({
  1133. model: Book
  1134. });
  1135. </pre>
  1136. <p id="Collection-constructor">
  1137. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  1138. <br />
  1139. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  1140. The collection's <a href="#Collection-comparator">comparator</a> function
  1141. may be included as an option. If you define an <b>initialize</b> function, it will be
  1142. invoked when the collection is created.
  1143. </p>
  1144. <pre>
  1145. var tabs = new TabSet([tab1, tab2, tab3]);
  1146. </pre>
  1147. <p id="Collection-models">
  1148. <b class="header">models</b><code>collection.models</code>
  1149. <br />
  1150. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  1151. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  1152. to access model objects, but occasionally a direct reference to the array
  1153. is desired.
  1154. </p>
  1155. <p id="Collection-toJSON">
  1156. <b class="header">toJSON</b><code>collection.toJSON()</code>
  1157. <br />
  1158. Return an array containing the attributes hash of each model in the
  1159. collection. This can be used to serialize and persist the
  1160. collection as a whole. The name of this method is a bit confusing, because
  1161. it conforms to
  1162. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  1163. </p>
  1164. <pre class="runnable">
  1165. var collection = new Backbone.Collection([
  1166. {name: "Tim", age: 5},
  1167. {name: "Ida", age: 26},
  1168. {name: "Rob", age: 55}
  1169. ]);
  1170. alert(JSON.stringify(collection));
  1171. </pre>
  1172. <p id="Collection-Underscore-Methods">
  1173. <b class="header">Underscore Methods (28)</b>
  1174. <br />
  1175. Backbone proxies to <b>Underscore.js</b> to provide 28 iteration functions
  1176. on <b>Backbone.Collection</b>. They aren't all documented here, but
  1177. you can take a look at the Underscore documentation for the full details&hellip;
  1178. </p>
  1179. <ul class="small">
  1180. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  1181. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  1182. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  1183. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  1184. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  1185. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  1186. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  1187. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  1188. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  1189. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  1190. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  1191. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  1192. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  1193. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  1194. <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li>
  1195. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  1196. <li><a href="http://documentcloud.github.com/underscore/#shuffle">shuffle</a></li>
  1197. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  1198. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  1199. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  1200. <li><a href="http://documentcloud.github.com/underscore/#initial">initial</a></li>
  1201. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  1202. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  1203. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  1204. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  1205. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  1206. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  1207. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  1208. </ul>
  1209. <pre>
  1210. Books.each(function(book) {
  1211. book.publish();
  1212. });
  1213. var titles = Books.map(function(book) {
  1214. return book.get("title");
  1215. });
  1216. var publishedBooks = Books.filter(function(book) {
  1217. return book.get("published") === true;
  1218. });
  1219. var alphabetical = Books.sortBy(function(book) {
  1220. return book.author.get("name").toLowerCase();
  1221. });
  1222. </pre>
  1223. <p id="Collection-add">
  1224. <b class="header">add</b><code>collection.add(models, [options])</code>
  1225. <br />
  1226. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  1227. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  1228. <a href="#Collection-model">model</a> property is defined, you may also pass
  1229. raw attributes objects, and have them be vivified as instances of the model.
  1230. Pass <tt>{at: index}</tt> to splice the model into the collection at the
  1231. specified <tt>index</tt>. Likewise, if you're a callback listening to a
  1232. collection's <tt>"add"</tt> event, <tt>options.index</tt> will tell you the
  1233. index at which the model is being added to the collection.
  1234. </p>
  1235. <pre class="runnable">
  1236. var ships = new Backbone.Collection;
  1237. ships.on("add", function(ship) {
  1238. alert("Ahoy " + ship.get("name") + "!");
  1239. });
  1240. ships.add([
  1241. {name: "Flying Dutchman"},
  1242. {name: "Black Pearl"}
  1243. ]);
  1244. </pre>
  1245. <p id="Collection-remove">
  1246. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  1247. <br />
  1248. Remove a model (or an array of models) from the collection. Fires a
  1249. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  1250. to suppress. If you're a callback listening to the <tt>"remove"</tt> event,
  1251. the index at which the model is being removed from the collection is available
  1252. as <tt>options.index</tt>.
  1253. </p>
  1254. <p id="Collection-get">
  1255. <b class="header">get</b><code>collection.get(id)</code>
  1256. <br />
  1257. Get a model from a collection, specified by <b>id</b>.
  1258. </p>
  1259. <pre>
  1260. var book = Library.get(110);
  1261. </pre>
  1262. <p id="Collection-getByCid">
  1263. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  1264. <br />
  1265. Get a model from a collection, specified by client id. The client id
  1266. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  1267. a model is created. Useful for models which have not yet been saved to
  1268. the server, and do not yet have true ids.
  1269. </p>
  1270. <p id="Collection-at">
  1271. <b class="header">at</b><code>collection.at(index)</code>
  1272. <br />
  1273. Get a model from a collection, specified by index. Useful if your collection
  1274. is sorted, and if your collection isn't sorted, <b>at</b> will still
  1275. retrieve models in insertion order.
  1276. </p>
  1277. <p id="Collection-push">
  1278. <b class="header">push</b><code>collection.push(model, [options])</code>
  1279. <br />
  1280. Add a model at the end of a collection. Takes the same options as
  1281. <a href="#Collection-add">add</a>.
  1282. </p>
  1283. <p id="Collection-pop">
  1284. <b class="header">pop</b><code>collection.pop([options])</code>
  1285. <br />
  1286. Remove and return the last model from a collection. Takes the same options as
  1287. <a href="#Collection-remove">remove</a>.
  1288. </p>
  1289. <p id="Collection-unshift">
  1290. <b class="header">unshift</b><code>collection.unshift(model, [options])</code>
  1291. <br />
  1292. Add a model at the beginning of a collection. Takes the same options as
  1293. <a href="#Collection-add">add</a>.
  1294. </p>
  1295. <p id="Collection-shift">
  1296. <b class="header">shift</b><code>collection.shift([options])</code>
  1297. <br />
  1298. Remove and return the first model from a collection. Takes the same options as
  1299. <a href="#Collection-remove">remove</a>.
  1300. </p>
  1301. <p id="Collection-length">
  1302. <b class="header">length</b><code>collection.length</code>
  1303. <br />
  1304. Like an array, a Collection maintains a <tt>length</tt> property, counting
  1305. the number of models it contains.
  1306. </p>
  1307. <p id="Collection-comparator">
  1308. <b class="header">comparator</b><code>collection.comparator</code>
  1309. <br />
  1310. By default there is no <b>comparator</b> function on a collection.
  1311. If you define a comparator, it will be used to maintain
  1312. the collection in sorted order. This means that as models are added,
  1313. they are inserted at the correct index in <tt>collection.models</tt>.
  1314. Comparator function can be defined as either a
  1315. <a href="http://underscorejs.org/#sortBy">sortBy</a>
  1316. (pass a function that takes a single argument),
  1317. or as a
  1318. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort">sort</a>
  1319. (pass a comparator function that expects two arguments).
  1320. </p>
  1321. <p>
  1322. "sortBy" comparator functions take a model and return a numeric or string
  1323. value by which the model should be ordered relative to others.
  1324. "sort" comparator functions take two models, and return <tt>-1</tt> if
  1325. the first model should come before the second, <tt>0</tt> if they are of
  1326. the same rank and <tt>1</tt> if the first model should come after.
  1327. </p>
  1328. <p>
  1329. Note how even though all of the chapters in this example are added backwards,
  1330. they come out in the proper order:
  1331. </p>
  1332. <pre class="runnable">
  1333. var Chapter = Backbone.Model;
  1334. var chapters = new Backbone.Collection;
  1335. chapters.comparator = function(chapter) {
  1336. return chapter.get("page");
  1337. };
  1338. chapters.add(new Chapter({page: 9, title: "The End"}));
  1339. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1340. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1341. alert(chapters.pluck('title'));
  1342. </pre>
  1343. <p class="warning">
  1344. Collections with comparator functions will not automatically re-sort if you
  1345. later change model attributes, so you may wish to call <tt>sort</tt> after
  1346. changing model attributes that would affect the order.
  1347. </p>
  1348. <p id="Collection-sort">
  1349. <b class="header">sort</b><code>collection.sort([options])</code>
  1350. <br />
  1351. Force a collection to re-sort itself. You don't need to call this under
  1352. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1353. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1354. triggers the collection's <tt>"reset"</tt> event, unless silenced by passing
  1355. <tt>{silent: true}</tt>
  1356. </p>
  1357. <p id="Collection-pluck">
  1358. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1359. <br />
  1360. Pluck an attribute from each model in the collection. Equivalent to calling
  1361. <tt>map</tt>, and returning a single attribute from the iterator.
  1362. </p>
  1363. <pre class="runnable">
  1364. var stooges = new Backbone.Collection([
  1365. {name: "Curly"},
  1366. {name: "Larry"},
  1367. {name: "Moe"}
  1368. ]);
  1369. var names = stooges.pluck("name");
  1370. alert(JSON.stringify(names));
  1371. </pre>
  1372. <p id="Collection-where">
  1373. <b class="header">where</b><code>collection.where(attributes)</code>
  1374. <br />
  1375. Return an array of all the models in a collection that match the
  1376. passed <b>attributes</b>. Useful for simple cases of <tt>filter</tt>.
  1377. </p>
  1378. <pre class="runnable">
  1379. var friends = new Backbone.Collection([
  1380. {name: "Athos", job: "Musketeer"},
  1381. {name: "Porthos", job: "Musketeer"},
  1382. {name: "Aramis", job: "Musketeer"},
  1383. {name: "d'Artagnan", job: "Guard"},
  1384. ]);
  1385. var musketeers = friends.where({job: "Musketeer"});
  1386. alert(musketeers.length);
  1387. </pre>
  1388. <p id="Collection-url">
  1389. <b class="header">url</b><code>collection.url or collection.url()</code>
  1390. <br />
  1391. Set the <b>url</b> property (or function) on a collection to reference
  1392. its location on the server. Models within the collection will use <b>url</b>
  1393. to construct URLs of their own.
  1394. </p>
  1395. <pre>
  1396. var Notes = Backbone.Collection.extend({
  1397. url: '/notes'
  1398. });
  1399. // Or, something more sophisticated:
  1400. var Notes = Backbone.Collection.extend({
  1401. url: function() {
  1402. return this.document.url() + '/notes';
  1403. }
  1404. });
  1405. </pre>
  1406. <p id="Collection-parse">
  1407. <b class="header">parse</b><code>collection.parse(response)</code>
  1408. <br />
  1409. <b>parse</b> is called by Backbone whenever a collection's models are
  1410. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1411. The function is passed the raw <tt>response</tt> object, and should return
  1412. the array of model attributes to be <a href="#Collection-add">added</a>
  1413. to the collection. The default implementation is a no-op, simply passing
  1414. through the JSON response. Override this if you need to work with a
  1415. preexisting API, or better namespace your responses. Note that afterwards,
  1416. if your model class already has a <tt>parse</tt> function, it will be
  1417. run against each fetched model.
  1418. </p>
  1419. <pre>
  1420. var Tweets = Backbone.Collection.extend({
  1421. // The Twitter Search API returns tweets under "results".
  1422. parse: function(response) {
  1423. return response.results;
  1424. }
  1425. });
  1426. </pre>
  1427. <p id="Collection-fetch">
  1428. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1429. <br />
  1430. Fetch the default set of models for this collection from the server,
  1431. resetting the collection when they arrive. The <b>options</b> hash takes
  1432. <tt>success</tt> and <tt>error</tt>
  1433. callbacks which will be passed <tt>(collection, response)</tt> as arguments.
  1434. When the model data returns from the server, the collection will
  1435. <a href="#Collection-reset">reset</a>.
  1436. Delegates to <a href="#Sync">Backbone.sync</a>
  1437. under the covers for custom persistence strategies and returns a
  1438. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>.
  1439. The server handler for <b>fetch</b> requests should return a JSON array of
  1440. models.
  1441. </p>
  1442. <pre class="runnable">
  1443. Backbone.sync = function(method, model) {
  1444. alert(method + ": " + model.url);
  1445. };
  1446. var Accounts = new Backbone.Collection;
  1447. Accounts.url = '/accounts';
  1448. Accounts.fetch();
  1449. </pre>
  1450. <p>
  1451. If you'd like to add the incoming models to the current collection, instead
  1452. of replacing the collection's contents, pass <tt>{add: true}</tt> as an
  1453. option to <b>fetch</b>.
  1454. </p>
  1455. <p>
  1456. <b>jQuery.ajax</b> options can also be passed directly as <b>fetch</b> options,
  1457. so to fetch a specific page of a paginated collection:
  1458. <tt>Documents.fetch({data: {page: 3}})</tt>
  1459. </p>
  1460. <p>
  1461. Note that <b>fetch</b> should not be used to populate collections on
  1462. page load &mdash; all models needed at load time should already be
  1463. <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
  1464. intended for lazily-loading models for interfaces that are not needed
  1465. immediately: for example, documents with collections of notes that may be
  1466. toggled open and closed.
  1467. </p>
  1468. <p id="Collection-reset">
  1469. <b class="header">reset</b><code>collection.reset(models, [options])</code>
  1470. <br />
  1471. Adding and removing models one at a time is all well and good, but sometimes
  1472. you have so many models to change that you'd rather just update the collection
  1473. in bulk. Use <b>reset</b> to replace a collection with a new list
  1474. of models (or attribute hashes), triggering a single <tt>"reset"</tt> event
  1475. at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"reset"</tt> event.
  1476. Using reset with no arguments is useful as a way to empty the collection.
  1477. </p>
  1478. <p>
  1479. Here's an example using <b>reset</b> to bootstrap a collection during initial page load,
  1480. in a Rails application.
  1481. </p>
  1482. <pre>
  1483. &lt;script&gt;
  1484. var Accounts = new Backbone.Collection;
  1485. Accounts.reset(&lt;%= @accounts.to_json %&gt;);
  1486. &lt;/script&gt;
  1487. </pre>
  1488. <p>
  1489. Calling <tt>collection.reset()</tt> without passing any models as arguments
  1490. will empty the entire collection.
  1491. </p>
  1492. <p id="Collection-create">
  1493. <b class="header">create</b><code>collection.create(attributes, [options])</code>
  1494. <br />
  1495. Convenience to create a new instance of a model within a collection.
  1496. Delegates to <a href="#Sync">Backbone.sync</a> and returns a
  1497. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a> if validation
  1498. is successful, and <tt>false</tt> otherwise.
  1499. Equivalent to instantiating a model with a hash of attributes,
  1500. saving the model to the server, and adding the model to the set after being
  1501. successfully created. Returns
  1502. the model, or <tt>false</tt> if a validation error prevented the
  1503. model from being created. In order for this to work, you should set the
  1504. <a href="#Collection-model">model</a> property of the collection.
  1505. The <b>create</b> method can accept either an attributes hash or an
  1506. existing, unsaved model object.
  1507. </p>
  1508. <p>
  1509. Creating a model will cause an immediate <tt>"add"</tt> event to be
  1510. triggered on the collection, as well as a <tt>"sync"</tt> event, once the
  1511. model has been successfully created on the server. Pass <tt>{wait: true}</tt>
  1512. if you'd like to wait for the server before adding the new model to the collection.
  1513. </p>
  1514. <pre>
  1515. var Library = Backbone.Collection.extend({
  1516. model: Book
  1517. });
  1518. var NYPL = new Library;
  1519. var othello = NYPL.create({
  1520. title: "Othello",
  1521. author: "William Shakespeare"
  1522. });
  1523. </pre>
  1524. <h2 id="Router">Backbone.Router</h2>
  1525. <p>
  1526. Web applications often provide linkable, bookmarkable, shareable URLs for
  1527. important locations in the app. Until recently, hash fragments
  1528. (<tt>#page</tt>) were used to provide these permalinks, but with the
  1529. arrival of the History API, it's now possible to use standard URLs (<tt>/page</tt>).
  1530. <b>Backbone.Router</b> provides methods for routing client-side pages, and
  1531. connecting them to actions and events. For browsers which don't yet support
  1532. the History API, the Router handles graceful fallback and transparent
  1533. translation to the fragment version of the URL.
  1534. </p>
  1535. <p>
  1536. During page load, after your application has finished creating all of its routers,
  1537. be sure to call <tt>Backbone.history.start()</tt>, or
  1538. <tt>Backbone.history.start({pushState: true})</tt> to route the initial URL.
  1539. </p>
  1540. <p id="Router-extend">
  1541. <b class="header">extend</b><code>Backbone.Router.extend(properties, [classProperties])</code>
  1542. <br />
  1543. Get started by creating a custom router class. Define actions that are
  1544. triggered when certain URL fragments are
  1545. matched, and provide a <a href="#Router-routes">routes</a> hash
  1546. that pairs routes to actions. Note that you'll want to avoid using a
  1547. leading slash in your route definitions:
  1548. </p>
  1549. <pre>
  1550. var Workspace = Backbone.Router.extend({
  1551. routes: {
  1552. "help": "help", // #help
  1553. "search/:query": "search", // #search/kiwis
  1554. "search/:query/p:page": "search" // #search/kiwis/p7
  1555. },
  1556. help: function() {
  1557. ...
  1558. },
  1559. search: function(query, page) {
  1560. ...
  1561. }
  1562. });
  1563. </pre>
  1564. <p id="Router-routes">
  1565. <b class="header">routes</b><code>router.routes</code>
  1566. <br />
  1567. The routes hash maps URLs with parameters to functions on your router,
  1568. similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
  1569. Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
  1570. component between slashes; and splat parts <tt>*splat</tt>, which can match
  1571. any number of URL components.
  1572. </p>
  1573. <p>
  1574. For example, a route of <tt>"search/:query/p:page"</tt> will match
  1575. a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
  1576. and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
  1577. match <tt>#file/nested/folder/file.txt</tt>,
  1578. passing <tt>"nested/folder/file.txt"</tt> to the action.
  1579. </p>
  1580. <p>
  1581. When the visitor presses the back button, or enters a URL, and a particular
  1582. route is matched, the name of the action will be fired as an
  1583. <a href="#Events">event</a>, so that other objects can listen to the router,
  1584. and be notified. In the following example, visiting <tt>#help/uploading</tt>
  1585. will fire a <tt>route:help</tt> event from the router.
  1586. </p>
  1587. <pre>
  1588. routes: {
  1589. "help/:page": "help",
  1590. "download/*path": "download",
  1591. "folder/:name": "openFolder",
  1592. "folder/:name-:mode": "openFolder"
  1593. }
  1594. </pre>
  1595. <pre>
  1596. router.on("route:help", function(page) {
  1597. ...
  1598. });
  1599. </pre>
  1600. <p id="Router-constructor">
  1601. <b class="header">constructor / initialize</b><code>new Router([options])</code>
  1602. <br />
  1603. When creating a new router, you may pass its
  1604. <a href="#Router-routes">routes</a> hash directly as an option, if you
  1605. choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
  1606. function, if defined.
  1607. </p>
  1608. <p id="Router-route">
  1609. <b class="header">route</b><code>router.route(route, name, [callback])</code>
  1610. <br />
  1611. Manually create a route for the router, The <tt>route</tt> argument may
  1612. be a <a href="#Router-routes">routing string</a> or regular expression.
  1613. Each matching capture from the route or regular expression will be passed as
  1614. an argument to the callback. The <tt>name</tt> argument will be triggered as
  1615. a <tt>"route:name"</tt> event whenever the route is matched. If the
  1616. <tt>callback</tt> argument is omitted <tt>router[name]</tt> will be used
  1617. instead.
  1618. </p>
  1619. <pre>
  1620. initialize: function(options) {
  1621. // Matches #page/10, passing "10"
  1622. this.route("page/:number", "page", function(number){ ... });
  1623. // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open
  1624. this.route(/^(.*?)\/open$/, "open");
  1625. },
  1626. open: function(id) { ... }
  1627. </pre>
  1628. <p id="Router-navigate">
  1629. <b class="header">navigate</b><code>router.navigate(fragment, [options])</code>
  1630. <br />
  1631. Whenever you reach a point in your application that you'd like to save
  1632. as a URL, call <b>navigate</b> in order to update the URL.
  1633. If you wish to also call the route function, set the <b>trigger</b>
  1634. option to <tt>true</tt>.
  1635. To update the URL without creating an entry in the browser's history,
  1636. set the <b>replace</b> option to <tt>true</tt>.
  1637. </p>
  1638. <pre>
  1639. openPage: function(pageNumber) {
  1640. this.document.pages.at(pageNumber).open();
  1641. this.navigate("page/" + pageNumber);
  1642. }
  1643. # Or ...
  1644. app.navigate("help/troubleshooting", {trigger: true});
  1645. # Or ...
  1646. app.navigate("help/troubleshooting", {trigger: true, replace: true});
  1647. </pre>
  1648. <h2 id="History">Backbone.history</h2>
  1649. <p>
  1650. <b>History</b> serves as a global router (per frame) to handle <tt>hashchange</tt>
  1651. events or <tt>pushState</tt>, match the appropriate route, and trigger callbacks. You shouldn't
  1652. ever have to create one of these yourself &mdash; you should use the reference
  1653. to <tt>Backbone.history</tt> that will be created for you automatically if you make use
  1654. of <a href="#Router">Routers</a> with <a href="#Router-routes">routes</a>.
  1655. </p>
  1656. <p>
  1657. <b>pushState</b> support exists on a purely opt-in basis in Backbone.
  1658. Older browsers that don't support <tt>pushState</tt> will continue to use
  1659. hash-based URL fragments, and if a hash URL is visited by a
  1660. <tt>pushState</tt>-capable browser, it will be transparently upgraded to
  1661. the true URL. Note that using real URLs requires your web server to be
  1662. able to correctly render those pages, so back-end changes are required
  1663. as well. For example, if you have a route of <tt>/documents/100</tt>,
  1664. your web server must be able to serve that page, if the browser
  1665. visits that URL directly. For full search-engine crawlability, it's best to
  1666. have the server generate the complete HTML for the page ... but if it's a web
  1667. application, just rendering the same content you would have for the root URL,
  1668. and filling in the rest with Backbone Views and JavaScript works fine.
  1669. </p>
  1670. <p id="History-start">
  1671. <b class="header">start</b><code>Backbone.history.start([options])</code>
  1672. <br />
  1673. When all of your <a href="#Router">Routers</a> have been created,
  1674. and all of the routes are set up properly, call <tt>Backbone.history.start()</tt>
  1675. to begin monitoring <tt>hashchange</tt> events, and dispatching routes.
  1676. </p>
  1677. <p>
  1678. To indicate that you'd like to use HTML5 <tt>pushState</tt> support in
  1679. your application, use <tt>Backbone.history.start({pushState: true})</tt>.
  1680. </p>
  1681. <p>
  1682. If your application is not being served from the root url <tt>/</tt> of your
  1683. domain, be sure to tell History where the root really is, as an option:
  1684. <tt>Backbone.history.start({pushState: true, root: "/public/search/"})</tt>
  1685. </p>
  1686. <p>
  1687. When called, if a route succeeds with a match for the current URL,
  1688. <tt>Backbone.history.start()</tt> returns <tt>true</tt>. If no defined
  1689. route matches the current URL, it returns <tt>false</tt>.
  1690. </p>
  1691. <p>
  1692. If the server has already rendered the entire page, and you don't want the
  1693. initial route to trigger when starting History, pass <tt>silent: true</tt>.
  1694. </p>
  1695. <p>
  1696. Because hash-based history in Internet Explorer relies on an
  1697. <tt>&lt;iframe&gt;</tt>, be sure to only call <tt>start()</tt> after the DOM
  1698. is ready.
  1699. </p>
  1700. <pre>
  1701. $(function(){
  1702. new WorkspaceRouter();
  1703. new HelpPaneRouter();
  1704. Backbone.history.start({pushState: true});
  1705. });
  1706. </pre>
  1707. <h2 id="Sync">Backbone.sync</h2>
  1708. <p>
  1709. <b>Backbone.sync</b> is the function that Backbone calls every time it
  1710. attempts to read or save a model to the server. By default, it uses
  1711. <tt>(jQuery/Zepto).ajax</tt> to make a RESTful JSON request and returns a
  1712. <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jqXHR</a>. You can override
  1713. it in order to use a different persistence strategy, such as WebSockets,
  1714. XML transport, or Local Storage.
  1715. </p>
  1716. <p>
  1717. The method signature of <b>Backbone.sync</b> is <tt>sync(method, model, [options])</tt>
  1718. </p>
  1719. <ul>
  1720. <li><b>method</b> the CRUD method (<tt>"create"</tt>, <tt>"read"</tt>, <tt>"update"</tt>, or <tt>"delete"</tt>)</li>
  1721. <li><b>model</b> the model to be saved (or collection to be read)</li>
  1722. <li><b>options</b> success and error callbacks, and all other jQuery request options</li>
  1723. </ul>
  1724. <p>
  1725. With the default implementation, when <b>Backbone.sync</b> sends up a request to save
  1726. a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body
  1727. with content-type <tt>application/json</tt>. When returning a JSON response,
  1728. send down the attributes of the model that have been changed by the server, and need
  1729. to be updated on the client. When responding to a <tt>"read"</tt> request from a collection
  1730. (<a href="#Collection#fetch">Collection#fetch</a>), send down an array
  1731. of model attribute objects.
  1732. </p>
  1733. <p>
  1734. The <b>sync</b> function may be overriden globally as <tt>Backbone.sync</tt>,
  1735. or at a finer-grained level, by adding a <tt>sync</tt> function to a Backbone
  1736. collection or to an individual model.
  1737. </p>
  1738. <p>
  1739. The default <b>sync</b> handler maps CRUD to REST like so:
  1740. </p>
  1741. <ul>
  1742. <li><b>create &rarr; POST &nbsp; </b><tt>/collection</tt></li>
  1743. <li><b>read &rarr; GET &nbsp; </b><tt>/collection[/id]</tt></li>
  1744. <li><b>update &rarr; PUT &nbsp; </b><tt>/collection/id</tt></li>
  1745. <li><b>delete &rarr; DELETE &nbsp; </b><tt>/collection/id</tt></li>
  1746. </ul>
  1747. <p>
  1748. As an example, a Rails handler responding to an <tt>"update"</tt> call from
  1749. <tt>Backbone</tt> might look like this: <i>(In real code, never use
  1750. </i><tt>update_attributes</tt><i> blindly, and always whitelist the attributes
  1751. you allow to be changed.)</i>
  1752. </p>
  1753. <pre>
  1754. def update
  1755. account = Account.find params[:id]
  1756. account.update_attributes params
  1757. render :json => account
  1758. end
  1759. </pre>
  1760. <p>
  1761. One more tip for Rails integration is to disable the default namespacing for
  1762. <tt>to_json</tt> calls on models by setting <tt>ActiveRecord::Base.include_root_in_json = false</tt>
  1763. </p>
  1764. <p id="Sync-emulateHTTP">
  1765. <b class="header">emulateHTTP</b><code>Backbone.emulateHTTP = true</code>
  1766. <br />
  1767. If you want to work with a legacy web server that doesn't support Backbones's
  1768. default REST/HTTP approach, you may choose to turn on <tt>Backbone.emulateHTTP</tt>.
  1769. Setting this option will fake <tt>PUT</tt> and <tt>DELETE</tt> requests with
  1770. a HTTP <tt>POST</tt>, setting the <tt>X-HTTP-Method-Override</tt> header
  1771. with the true method. If <tt>emulateJSON</tt> is also on, the true method
  1772. will be passed as an additional <tt>_method</tt> parameter.
  1773. </p>
  1774. <pre>
  1775. Backbone.emulateHTTP = true;
  1776. model.save(); // POST to "/collection/id", with "_method=PUT" + header.
  1777. </pre>
  1778. <p id="Sync-emulateJSON">
  1779. <b class="header">emulateJSON</b><code>Backbone.emulateJSON = true</code>
  1780. <br />
  1781. If you're working with a legacy web server that can't handle requests
  1782. encoded as <tt>application/json</tt>, setting <tt>Backbone.emulateJSON = true;</tt>
  1783. will cause the JSON to be serialized under a <tt>model</tt> parameter, and
  1784. the request to be made with a <tt>application/x-www-form-urlencoded</tt>
  1785. mime type, as if from an HTML form.
  1786. </p>
  1787. <h2 id="View">Backbone.View</h2>
  1788. <p>
  1789. Backbone views are almost more convention than they are code &mdash; they
  1790. don't determine anything about your HTML or CSS for you, and can be used
  1791. with any JavaScript templating library.
  1792. The general idea is to organize your interface into logical views,
  1793. backed by models, each of which can be updated independently when the
  1794. model changes, without having to redraw the page. Instead of digging into
  1795. a JSON object, looking up an element in the DOM, and updating the HTML by hand,
  1796. you can bind your view's <tt>render</tt> function to the model's <tt>"change"</tt>
  1797. event &mdash; and now everywhere that
  1798. model data is displayed in the UI, it is always immediately up to date.
  1799. </p>
  1800. <p id="View-extend">
  1801. <b class="header">extend</b><code>Backbone.View.extend(properties, [classProperties])</code>
  1802. <br />
  1803. Get started with views by creating a custom view class. You'll want to
  1804. override the <a href="#View-render">render</a> function, specify your
  1805. declarative <a href="#View-delegateEvents">events</a>, and perhaps the
  1806. <tt>tagName</tt>, <tt>className</tt>, or <tt>id</tt> of the View's root
  1807. element.
  1808. </p>
  1809. <pre>
  1810. var DocumentRow = Backbone.View.extend({
  1811. tagName: "li",
  1812. className: "document-row",
  1813. events: {
  1814. "click .icon": "open",
  1815. "click .button.edit": "openEditDialog",
  1816. "click .button.delete": "destroy"
  1817. },
  1818. render: function() {
  1819. ...
  1820. }
  1821. });
  1822. </pre>
  1823. <p id="View-constructor">
  1824. <b class="header">constructor / initialize</b><code>new View([options])</code>
  1825. <br />
  1826. When creating a new View, the options you pass are attached to the view
  1827. as <tt>this.options</tt>, for future reference. There are several special
  1828. options that, if passed, will be attached directly to the view:
  1829. <tt>model</tt>, <tt>collection</tt>,
  1830. <tt>el</tt>, <tt>id</tt>, <tt>className</tt>, <tt>tagName</tt> and <tt>attributes</tt>.
  1831. If the view defines an <b>initialize</b> function, it will be called when
  1832. the view is first created. If you'd like to create a view that references
  1833. an element <i>already</i> in the DOM, pass in the element as an option:
  1834. <tt>new View({el: existingElement})</tt>
  1835. </p>
  1836. <pre>
  1837. var doc = Documents.first();
  1838. new DocumentRow({
  1839. model: doc,
  1840. id: "document-row-" + doc.id
  1841. });
  1842. </pre>
  1843. <p id="View-el">
  1844. <b class="header">el</b><code>view.el</code>
  1845. <br />
  1846. All views have a DOM element at all times (the <b>el</b> property),
  1847. whether they've already been inserted into the page or not. In this
  1848. fashion, views can be rendered at any time, and inserted into the DOM all
  1849. at once, in order to get high-performance UI rendering with as few
  1850. reflows and repaints as possible. <tt>this.el</tt> is created from the
  1851. view's <tt>tagName</tt>, <tt>className</tt>, <tt>id</tt> and <tt>attributes</tt> properties,
  1852. if specified. If not, <b>el</b> is an empty <tt>div</tt>.
  1853. </p>
  1854. <pre class="runnable">
  1855. var ItemView = Backbone.View.extend({
  1856. tagName: 'li'
  1857. });
  1858. var BodyView = Backbone.View.extend({
  1859. el: 'body'
  1860. });
  1861. var item = new ItemView();
  1862. var body = new BodyView();
  1863. alert(item.el + ' ' + body.el);
  1864. </pre>
  1865. <p id="View-$el">
  1866. <b class="header">$el</b><code>view.$el</code>
  1867. <br />
  1868. A cached jQuery (or Zepto) object for the view's element. A handy
  1869. reference instead of re-wrapping the DOM element all the time.
  1870. </p>
  1871. <pre>
  1872. view.$el.show();
  1873. listView.$el.append(itemView.el);
  1874. </pre>
  1875. <p id="View-setElement">
  1876. <b class="header">setElement</b><code>view.setElement(element)</code>
  1877. <br />
  1878. If you'd like to apply a Backbone view to a different DOM element, use
  1879. <b>setElement</b>, which will also create the cached <tt>$el</tt> reference
  1880. and move the view's delegated events from the old element to the new one.
  1881. </p>
  1882. <p id="View-attributes">
  1883. <b class="header">attributes</b><code>view.attributes</code>
  1884. <br />
  1885. A hash of attributes that will be set as HTML DOM element attributes on the
  1886. view's <tt>el</tt> (id, class, data-properties, etc.), or a function that
  1887. returns such a hash.
  1888. </p>
  1889. <p id="View-dollar">
  1890. <b class="header">$ (jQuery or Zepto)</b><code>view.$(selector)</code>
  1891. <br />
  1892. If jQuery or Zepto is included on the page, each view has a
  1893. <b>$</b> function that runs queries scoped within the view's element. If you use this
  1894. scoped jQuery function, you don't have to use model ids as part of your query
  1895. to pull out specific elements in a list, and can rely much more on HTML class
  1896. attributes. It's equivalent to running: <tt>view.$el.find(selector)</tt>
  1897. </p>
  1898. <pre>
  1899. ui.Chapter = Backbone.View.extend({
  1900. serialize : function() {
  1901. return {
  1902. title: this.$(".title").text(),
  1903. start: this.$(".start-page").text(),
  1904. end: this.$(".end-page").text()
  1905. };
  1906. }
  1907. });
  1908. </pre>
  1909. <p id="View-render">
  1910. <b class="header">render</b><code>view.render()</code>
  1911. <br />
  1912. The default implementation of <b>render</b> is a no-op. Override this
  1913. function with your code that renders the view template from model data,
  1914. and updates <tt>this.el</tt> with the new HTML. A good
  1915. convention is to <tt>return this</tt> at the end of <b>render</b> to
  1916. enable chained calls.
  1917. </p>
  1918. <pre>
  1919. var Bookmark = Backbone.View.extend({
  1920. render: function() {
  1921. $(this.el).html(this.template(this.model.toJSON()));
  1922. return this;
  1923. }
  1924. });
  1925. </pre>
  1926. <p>
  1927. Backbone is agnostic with respect to your preferred method of HTML templating.
  1928. Your <b>render</b> function could even munge together an HTML string, or use
  1929. <tt>document.createElement</tt> to generate a DOM tree. However, we suggest
  1930. choosing a nice JavaScript templating library.
  1931. <a href="http://github.com/janl/mustache.js">Mustache.js</a>,
  1932. <a href="http://github.com/creationix/haml-js">Haml-js</a>, and
  1933. <a href="http://github.com/sstephenson/eco">Eco</a> are all fine alternatives.
  1934. Because <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> is already on the page,
  1935. <a href="http://documentcloud.github.com/underscore/#template">_.template</a>
  1936. is available, and is an excellent choice if you've already XSS-sanitized
  1937. your interpolated data.
  1938. </p>
  1939. <p>
  1940. Whatever templating strategy you end up with, it's nice if you <i>never</i>
  1941. have to put strings of HTML in your JavaScript. At DocumentCloud, we
  1942. use <a href="http://documentcloud.github.com/jammit/">Jammit</a> in order
  1943. to package up JavaScript templates stored in <tt>/app/views</tt> as part
  1944. of our main <tt>core.js</tt> asset package.
  1945. </p>
  1946. <p id="View-remove">
  1947. <b class="header">remove</b><code>view.remove()</code>
  1948. <br />
  1949. Convenience function for removing the view from the DOM. Equivalent to calling
  1950. <tt>$(view.el).remove();</tt>
  1951. </p>
  1952. <p id="View-make">
  1953. <b class="header">make</b><code>view.make(tagName, [attributes], [content])</code>
  1954. <br />
  1955. Convenience function for creating a DOM element of the given type (<b>tagName</b>),
  1956. with optional attributes and HTML content. Used internally to create the
  1957. initial <tt>view.el</tt>.
  1958. </p>
  1959. <pre class="runnable">
  1960. var view = new Backbone.View;
  1961. var el = view.make("b", {"class": "bold"}, "Bold! ");
  1962. $("#make-demo").append(el);
  1963. </pre>
  1964. <div id="make-demo"></div>
  1965. <p id="View-delegateEvents">
  1966. <b class="header">delegateEvents</b><code>delegateEvents([events])</code>
  1967. <br />
  1968. Uses jQuery's <tt>delegate</tt> function to provide declarative callbacks
  1969. for DOM events within a view.
  1970. If an <b>events</b> hash is not passed directly, uses <tt>this.events</tt>
  1971. as the source. Events are written in the format <tt>{"event selector": "callback"}</tt>.
  1972. The callback may be either the name of a method on the view, or a direct
  1973. function body.
  1974. Omitting the <tt>selector</tt> causes the event to be bound to the view's
  1975. root element (<tt>this.el</tt>). By default, <tt>delegateEvents</tt> is called
  1976. within the View's constructor for you, so if you have a simple <tt>events</tt>
  1977. hash, all of your DOM events will always already be connected, and you will
  1978. never have to call this function yourself.
  1979. </p>
  1980. <p>
  1981. The <tt>events</tt> property may also be defined as a function that returns
  1982. an <b>events</b> hash, to make it easier to programmatically define your
  1983. events, as well as inherit them from parent views.
  1984. </p>
  1985. <p>
  1986. Using <b>delegateEvents</b> provides a number of advantages over manually
  1987. using jQuery to bind events to child elements during <a href="#View-render">render</a>. All attached
  1988. callbacks are bound to the view before being handed off to jQuery, so when
  1989. the callbacks are invoked, <tt>this</tt> continues to refer to the view object. When
  1990. <b>delegateEvents</b> is run again, perhaps with a different <tt>events</tt>
  1991. hash, all callbacks are removed and delegated afresh &mdash; useful for
  1992. views which need to behave differently when in different modes.
  1993. </p>
  1994. <p>
  1995. A view that displays a document in a search result might look
  1996. something like this:
  1997. </p>
  1998. <pre>
  1999. var DocumentView = Backbone.View.extend({
  2000. events: {
  2001. "dblclick" : "open",
  2002. "click .icon.doc" : "select",
  2003. "contextmenu .icon.doc" : "showMenu",
  2004. "click .show_notes" : "toggleNotes",
  2005. "click .title .lock" : "editAccessLevel",
  2006. "mouseover .title .date" : "showTooltip"
  2007. },
  2008. render: function() {
  2009. $(this.el).html(this.template(this.model.toJSON()));
  2010. return this;
  2011. },
  2012. open: function() {
  2013. window.open(this.model.get("viewer_url"));
  2014. },
  2015. select: function() {
  2016. this.model.set({selected: true});
  2017. },
  2018. ...
  2019. });
  2020. </pre>
  2021. <p id="View-undelegateEvents">
  2022. <b class="header">undelegateEvents</b><code>undelegateEvents()</code>
  2023. <br />
  2024. Removes all of the view's delegated events. Useful if you want to disable
  2025. or remove a view from the DOM temporarily.
  2026. </p>
  2027. <h2 id="Utility">Utility Functions</h2>
  2028. <p id="Utility-noConflict">
  2029. <b class="header">noConflict</b><code>var backbone = Backbone.noConflict();</code>
  2030. <br />
  2031. Returns the <tt>Backbone</tt> object back to its original value. You can
  2032. use the return value of <tt>Backbone.noConflict()</tt> to keep a local
  2033. reference to Backbone. Useful for embedding Backbone on third-party
  2034. websites, where you don't want to clobber the existing Backbone.
  2035. </p>
  2036. <pre>
  2037. var localBackbone = Backbone.noConflict();
  2038. var model = localBackbone.Model.extend(...);
  2039. </pre>
  2040. <p id="Utility-setDomLibrary">
  2041. <b class="header">setDomLibrary</b><code>Backbone.setDomLibrary(jQueryNew);</code>
  2042. <br />
  2043. If you have multiple copies of <tt>jQuery</tt> on the page, or simply want
  2044. to tell Backbone to use a particular object as its DOM / Ajax library,
  2045. this is the function for you.
  2046. </p>
  2047. <h2 id="examples">Examples</h2>
  2048. <p>
  2049. The list of examples that follows, while long, is not exhaustive. If you've
  2050. worked on an app that uses Backbone, please add it to the
  2051. <a href="https://github.com/documentcloud/backbone/wiki/Projects-and-Companies-using-Backbone">wiki page of Backbone apps</a>.
  2052. </p>
  2053. <p id="examples-todos">
  2054. <a href="http://jgn.me/">Jérôme Gravel-Niquet</a> has contributed a
  2055. <a href="examples/todos/index.html">Todo List application</a>
  2056. that is bundled in the repository as Backbone example. If you're wondering
  2057. where to get started with Backbone in general, take a moment to
  2058. <a href="docs/todos.html">read through the annotated source</a>. The app uses a
  2059. <a href="docs/backbone-localstorage.html">LocalStorage adapter</a>
  2060. to transparently save all of your todos within your browser, instead of
  2061. sending them to a server. Jérôme also has a version hosted at
  2062. <a href="http://localtodos.com/">localtodos.com</a> that uses a
  2063. <a href="http://github.com/jeromegn/backbone-mootools">MooTools-backed version of Backbone</a>
  2064. instead of jQuery.
  2065. </p>
  2066. <div style="text-align: center;">
  2067. <a href="examples/todos/index.html">
  2068. <img src="docs/images/todos.png" alt="Todos" class="example_image" />
  2069. </a>
  2070. </div>
  2071. <h2 id="examples-documentcloud">DocumentCloud</h2>
  2072. <p>
  2073. The <a href="http://www.documentcloud.org/public/#search/">DocumentCloud workspace</a>
  2074. is built on Backbone.js, with <i>Documents</i>, <i>Projects</i>,
  2075. <i>Notes</i>, and <i>Accounts</i> all as Backbone models and collections.
  2076. If you're interested in history &mdash; both Underscore.js and Backbone.js
  2077. were originally extracted from the DocumentCloud codebase, and packaged
  2078. into standalone JS libraries.
  2079. </p>
  2080. <div style="text-align: center;">
  2081. <a href="http://www.documentcloud.org/public/#search/">
  2082. <img src="docs/images/dc-workspace.png" alt="DocumentCloud Workspace" class="example_image" />
  2083. </a>
  2084. </div>
  2085. <h2 id="examples-linkedin">LinkedIn Mobile</h2>
  2086. <p>
  2087. <a href="http://www.linkedin.com/">LinkedIn</a> used Backbone.js to create
  2088. its <a href="http://www.linkedin.com/static?key=mobile">next-generation HTML5 mobile web app</a>.
  2089. Backbone made it easy to keep the app modular, organized and extensible so
  2090. that it was possible to program the complexities of LinkedIn's user experience.
  2091. The app also uses <a href="http://zeptojs.com/">Zepto</a>,
  2092. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>,
  2093. <a href="http://sass-lang.com/">SASS</a>, <a href="http://cubiq.org/iscroll">iScroll</a>,
  2094. HTML5 LocalStorage and Canvas.
  2095. </p>
  2096. <div style="text-align: center;">
  2097. <a href="http://www.linkedin.com/static?key=mobile">
  2098. <img src="docs/images/linkedin-mobile.png" alt="LinkedIn Mobile" class="example_image" />
  2099. </a>
  2100. </div>
  2101. <h2 id="examples-flow">Flow</h2>
  2102. <p>
  2103. <a href="http://www.metalabdesign.com/">MetaLab</a> used Backbone.js to create
  2104. <a href="http://www.getflow.com/">Flow</a>, a task management app for teams. The
  2105. workspace relies on Backbone.js to construct task views, activities, accounts,
  2106. folders, projects, and tags. You can see the internals under <tt>window.Flow</tt>.
  2107. </p>
  2108. <div style="text-align: center;">
  2109. <a href="http://www.getflow.com/">
  2110. <img src="docs/images/flow.png" alt="Flow" class="example_image" />
  2111. </a>
  2112. </div>
  2113. <h2 id="examples-audiovroom">AudioVroom</h2>
  2114. <p>
  2115. <a href="http://www.audiovroom.com/">AudioVroom</a> is a free music
  2116. streaming app that allows you to listen to your Facebook friends like
  2117. radio stations. It relies heavily on Backbone (views and song management)
  2118. and also features a responsive grid-based design (using CSS3 media-queries)
  2119. to deliver a unified user experience on desktops, mobiles, and tablets alike.
  2120. Being a pure Backbone app, AudioVroom is only 60kb compressed, and can be
  2121. entirely hosted on the CDN.
  2122. </p>
  2123. <div style="text-align: center;">
  2124. <a href="http://www.audiovroom.com/">
  2125. <img src="docs/images/audiovroom.png" alt="AudioVroom" class="example_image" />
  2126. </a>
  2127. </div>
  2128. <h2 id="examples-foursquare">Foursquare</h2>
  2129. <p>
  2130. Foursquare is a fun little startup that helps you meet up with friends,
  2131. discover new places, and save money. Backbone Models are heavily used in
  2132. the core JavaScript API layer and Views power many popular features like
  2133. the <a href="https://foursquare.com">homepage map</a> and
  2134. <a href="https://foursquare.com/seriouseats/list/the-best-doughnuts-in-ny">lists</a>.
  2135. </p>
  2136. <div style="text-align: center;">
  2137. <a href="http://foursquare.com">
  2138. <img src="docs/images/foursquare.png" alt="Foursquare" class="example_image" />
  2139. </a>
  2140. </div>
  2141. <h2 id="examples-wunderkit">Wunderkit</h2>
  2142. <p>
  2143. <a href="http://get.wunderkit.com/">Wunderkit</a> is a productivity and
  2144. social collaboration platform. It
  2145. uses Backbone.js as the foundation for the single-page application,
  2146. which is backed by a RESTful Rails API.
  2147. The freedom and agility that Backbone gives to developers
  2148. made it possible to build Wunderkit in a very short time and
  2149. extend it with custom features: a write-through cache using HTML5
  2150. localStorage, and a view hierarchy extension to easily manage trees of
  2151. sub-views. Aside from Backbone, Wunderkit also
  2152. depends on <a href="http://jquery.com/">jQuery</a>, <a href="http://underscorejs.org/">Underscore</a>, <a href="http://requirejs.org/">Require.js</a>, <a href="http://lesscss.org/">LESS</a> and doT.js templates.
  2153. </p>
  2154. <div style="text-align: center;">
  2155. <a href="http://get.wunderkit.com/">
  2156. <img src="docs/images/wunderkit.png" alt="Wunderkit" class="example_image" />
  2157. </a>
  2158. </div>
  2159. <h2 id="examples-khan-academy">Khan Academy</h2>
  2160. <p>
  2161. <a href="http://www.khanacademy.org">Khan Academy</a> is on a mission to
  2162. provide a free world-class education to anyone anywhere. With thousands of
  2163. videos, hundreds of JavaScript-driven exercises, and big plans for the
  2164. future, Khan Academy uses Backbone to keep frontend code modular and organized.
  2165. <a href="https://khanacademy.kilnhg.com/Code/Website/Group/stable/Files/javascript/profile-package?rev=tip">User profiles</a>
  2166. and <a href="https://khanacademy.kilnhg.com/Code/Website/Group/stable/File/javascript/shared-package/goals.js?rev=tip">goal setting</a>
  2167. are implemented with Backbone, <a href="http://jquery.com/">jQuery</a> and <a href="http://handlebarsjs.com/">Handlebars</a>, and most new feature
  2168. work is being pushed to the client side, greatly increasing the quality of
  2169. <a href="https://github.com/Khan/khan-api/">the API</a>.
  2170. </p>
  2171. <div style="text-align: center;">
  2172. <a href="http://www.khanacademy.org">
  2173. <img src="docs/images/khan-academy.png" alt="Khan Academy" class="example_image" />
  2174. </a>
  2175. </div>
  2176. <h2 id="examples-do">Do</h2>
  2177. <p>
  2178. <a href="http://do.com">Do</a> is a social productivity app that makes it
  2179. easy to work on tasks, track projects, and take notes with your team.
  2180. The <a href="http://do.com">Do.com</a> web application was built from the
  2181. ground up to work seamlessly on your smartphone, tablet and computer. The
  2182. team used Backbone, <a href="http://coffeescript.org/">CoffeeScript</a> and <a href="http://handlebarsjs.com/">Handlebars</a> to build a full-featured
  2183. app in record time and rolled their own extensions for complex navigation
  2184. and model sync support.
  2185. </p>
  2186. <div style="text-align: center;">
  2187. <a href="http://do.com">
  2188. <img src="docs/images/do.png" alt="Do" class="example_image" />
  2189. </a>
  2190. </div>
  2191. <h2 id="examples-posterous">Posterous</h2>
  2192. <p>
  2193. <a href="https://posterous.com/">Posterous Spaces</a> is
  2194. <a href="http://technology.posterous.com/posterous-spaces-is-built-on-backbonejs">built on Backbone</a>.
  2195. The models and collections mirror the public
  2196. <a href="http://posterous.com/api">Posterous API</a>. Backbone made it easy
  2197. for the team to create a JavaScript-heavy application with complex
  2198. interactions and state maintenance. Spaces also uses <a href="http://coffeescript.org/">CoffeeScript</a>,
  2199. <a href="http://underscorejs.org/">Underscore.js</a>, <a href="https://github.com/creationix/haml-js">Haml.js</a>, <a href="http://sass-lang.com/">Sass</a>, <a href="http://compass-style.org/">Compass</a>, and of course <a href="http://jquery.com">jQuery</a>.
  2200. </p>
  2201. <div style="text-align: center;">
  2202. <a href="https://posterous.com/">
  2203. <img src="docs/images/posterous-spaces.png" alt="Posterous Spaces" class="example_image" />
  2204. </a>
  2205. </div>
  2206. <h2 id="examples-groupon">Groupon Now!</h2>
  2207. <p>
  2208. <a href="http://www.groupon.com/now">Groupon Now!</a> helps you find
  2209. local deals that you can buy and use right now. When first developing
  2210. the product, the team decided it would be AJAX heavy with smooth transitions
  2211. between sections instead of full refreshes, but still needed to be fully
  2212. linkable and shareable. Despite never having used Backbone before, the
  2213. learning curve was incredibly quick &mdash; a prototype was hacked out in an
  2214. afternoon, and the team was able to ship the product in two weeks.
  2215. Because the source is minimal and understandable, it was easy to
  2216. add several Backbone extensions for Groupon Now!: changing the router
  2217. to handle URLs with querystring parameters, and adding a simple
  2218. in-memory store for caching repeated requests for the same data.
  2219. </p>
  2220. <div style="text-align: center;">
  2221. <a href="http://www.groupon.com/now">
  2222. <img src="docs/images/groupon.png" alt="Groupon Now!" class="example_image" />
  2223. </a>
  2224. </div>
  2225. <h2 id="examples-basecamp">Basecamp Mobile</h2>
  2226. <p>
  2227. <a href="http://37signals.com/">37Signals</a> used Backbone.js to create
  2228. <a href="http://basecamphq.com/mobile">Basecamp Mobile</a>, the mobile version
  2229. of their popular project management software. You can access all your Basecamp
  2230. projects, post new messages, and comment on milestones (all represented
  2231. internally as Backbone.js models).
  2232. </p>
  2233. <div style="text-align: center;">
  2234. <a href="http://basecamphq.com/mobile">
  2235. <img src="docs/images/basecamp-mobile.png" alt="Basecamp Mobile" class="example_image" />
  2236. </a>
  2237. </div>
  2238. <h2 id="examples-slavery-footprint">Slavery Footprint</h2>
  2239. <p>
  2240. <a href="http://slaveryfootprint.org/survey">Slavery Footprint</a>
  2241. allows consumers to visualize how their consumption habits are
  2242. connected to modern-day slavery and provides them with an opportunity
  2243. to have a deeper conversation with the companies that manufacture the
  2244. goods they purchased.
  2245. Based in Oakland, California, the Slavery Footprint team works to engage
  2246. individuals, groups, and businesses to build awareness for and create
  2247. deployable action against forced labor, human trafficking, and modern-day
  2248. slavery through online tools, as well as off-line community education and
  2249. mobilization programs.
  2250. </p>
  2251. <div style="text-align: center;">
  2252. <a href="http://slaveryfootprint.org/survey">
  2253. <img src="docs/images/slavery-footprint.png" alt="Slavery Footprint" class="example_image" />
  2254. </a>
  2255. </div>
  2256. <h2 id="examples-stripe">Stripe</h2>
  2257. <p>
  2258. <a href="https://stripe.com">Stripe</a> provides an API for accepting
  2259. credit cards on the web. Stripe's
  2260. <a href="https://manage.stripe.com">management interface</a> was recently
  2261. rewritten from scratch in Coffeescript using Backbone.js as the primary
  2262. framework, <a href="https://github.com/sstephenson/eco">Eco</a> for templates, <a href="http://sass-lang.com/">Sass</a> for stylesheets, and <a href="https://github.com/sstephenson/stitch">Stitch</a> to package
  2263. everything together as <a href="http://commonjs.org/">CommonJS</a> modulas. The new app uses
  2264. <a href="https://stripe.com/docs/api">Stripe's API</a> directly for the
  2265. majority of its actions; Backbone.js models made it simple to map
  2266. client-side models to their corresponding RESTful resources.
  2267. </p>
  2268. <div style="text-align: center;">
  2269. <a href="https://stripe.com">
  2270. <img src="docs/images/stripe.png" alt="Stripe" class="example_image" />
  2271. </a>
  2272. </div>
  2273. <h2 id="examples-airbnb">Airbnb Mobile</h2>
  2274. <p>
  2275. <a href="http://airbnb.com">Airbnb</a> used Backbone.js and
  2276. <a href="http://coffeescript.org">CoffeeScript</a> to quickly build
  2277. <a href="http://m.airbnb.com">Airbnb Mobile</a>
  2278. in six weeks with a team of three. The mobile version of Airbnb lets you
  2279. discover and book rental spaces directly from your phone: from a private
  2280. apartment to a private island...
  2281. </p>
  2282. <div style="text-align: center;">
  2283. <a href="http://m.airbnb.com/">
  2284. <img src="docs/images/airbnb-mobile.png" alt="Airbnb-Mobile" class="example_image" />
  2285. </a>
  2286. </div>
  2287. <h2 id="examples-diaspora">Diaspora</h2>
  2288. <p>
  2289. <a href="http://www.joindiaspora.com/">Diaspora</a> is a distributed social
  2290. network, formed from a number of independently operated <i>pods</i>.
  2291. You own your personal data, and control with whom you share.
  2292. All of Diaspora is <a href="https://github.com/diaspora/diaspora">open-source</a>
  2293. code, built with <a href="http://rubyonrails.org/">Rails</a> and Backbone.js.
  2294. </p>
  2295. <div style="text-align: center;">
  2296. <a href="http://www.joindiaspora.com/">
  2297. <img src="docs/images/diaspora.png" alt="Diaspora" class="example_image" />
  2298. </a>
  2299. </div>
  2300. <h2 id="examples-soundcloud">SoundCloud Mobile</h2>
  2301. <p>
  2302. <a href="http://soundcloud.com">SoundCloud</a> is the leading sound sharing
  2303. platform on the internet, and Backbone.js provides the foundation for
  2304. <a href="http://m.soundcloud.com">SoundCloud Mobile</a>. The project uses
  2305. the public SoundCloud <a href="http://soundcloud.com/developers">API</a>
  2306. as a data source (channeled through a nginx proxy),
  2307. <a href="http://api.jquery.com/category/plugins/templates/">jQuery templates</a>
  2308. for the rendering, <a href="http://docs.jquery.com/Qunit">Qunit
  2309. </a> and <a href="http://www.phantomjs.org/">PhantomJS</a> for
  2310. the testing suite. The JS code, templates and CSS are built for the
  2311. production deployment with various Node.js tools like
  2312. <a href="https://github.com/dsimard/ready.js">ready.js</a>,
  2313. <a href="https://github.com/mde/jake">Jake</a>,
  2314. <a href="https://github.com/tmpvar/jsdom">jsdom</a>.
  2315. The <b>Backbone.History</b> was modified to support the HTML5 <tt>history.pushState</tt>.
  2316. <b>Backbone.sync</b> was extended with an additional SessionStorage based cache
  2317. layer.
  2318. </p>
  2319. <div style="text-align: center;">
  2320. <a href="http://m.soundcloud.com">
  2321. <img src="docs/images/soundcloud.png" alt="SoundCloud" class="example_image" />
  2322. </a>
  2323. </div>
  2324. <h2 id="examples-pandora">Pandora</h2>
  2325. <p>
  2326. When <a href="http://www.pandora.com/newpandora">Pandora</a> redesigned
  2327. their site in HTML5, they chose Backbone.js to help
  2328. manage the user interface and interactions. For example, there's a model
  2329. that represents the "currently playing track", and multiple views that
  2330. automatically update when the current track changes. The station list is a
  2331. collection, so that when stations are added or changed, the UI stays up to date.
  2332. </p>
  2333. <div style="text-align: center;">
  2334. <a href="http://www.pandora.com/newpandora">
  2335. <img src="docs/images/pandora.png" alt="Pandora" class="example_image" />
  2336. </a>
  2337. </div>
  2338. <h2 id="examples-code-school">Code School</h2>
  2339. <p>
  2340. <a href="http://www.codeschool.com">Code School</a> courses teach people
  2341. about various programming topics like <a href="http://coffeescript.org">CoffeeScript</a>, CSS, Ruby on Rails,
  2342. and more. The new Code School course
  2343. <a href="http://coffeescript.codeschool.com/levels/1/challenges/1">challenge page</a>
  2344. is built from the ground up on Backbone.js, using
  2345. everything it has to offer: the router, collections, models, and complex
  2346. event handling. Before, the page was a mess of <a href="http://jquery.com/">jQuery</a> DOM manipulation
  2347. and manual Ajax calls. Backbone.js helped introduce a new way to
  2348. think about developing an organized front-end application in Javascript.
  2349. </p>
  2350. <div style="text-align: center;">
  2351. <a href="http://www.codeschool.com">
  2352. <img src="docs/images/code-school.png" alt="Code School" class="example_image" />
  2353. </a>
  2354. </div>
  2355. <h2 id="examples-cloudapp">CloudApp</h2>
  2356. <p>
  2357. <a href="http://getcloudapp.com">CloudApp</a> is simple file and link
  2358. sharing for the Mac. Backbone.js powers the web tools
  2359. which consume the <a href="http://developer.getcloudapp.com">documented API</a>
  2360. to manage Drops. Data is either pulled manually or pushed by
  2361. <a href="http://pusher.com">Pusher</a> and fed to
  2362. <a href="http://github.com/janl/mustache.js">Mustache</a> templates for
  2363. rendering. Check out the <a href="http://cloudapp.github.com/engine">annotated source code</a>
  2364. to see the magic.
  2365. </p>
  2366. <div style="text-align: center;">
  2367. <a href="http://getcloudapp.com">
  2368. <img src="docs/images/cloudapp.png" alt="CloudApp" class="example_image" />
  2369. </a>
  2370. </div>
  2371. <h2 id="examples-seatgeek">SeatGeek</h2>
  2372. <p>
  2373. <a href="http://seatgeek.com">SeatGeek</a>'s stadium ticket maps were originally
  2374. developed with <a href="http://prototypejs.org/">Prototype.js</a>. Moving to Backbone.js and <a href="http://jquery.com/">jQuery</a> helped organize
  2375. a lot of the UI code, and the increased structure has made adding features
  2376. a lot easier. SeatGeek is also in the process of building a mobile
  2377. interface that will be Backbone.js from top to bottom.
  2378. </p>
  2379. <div style="text-align: center;">
  2380. <a href="http://seatgeek.com">
  2381. <img src="docs/images/seatgeek.png" alt="SeatGeek" class="example_image" />
  2382. </a>
  2383. </div>
  2384. <h2 id="examples-grove">Grove.io</h2>
  2385. <p>
  2386. <a href="http://grove.io">Grove.io</a> provides hosted IRC for teams.
  2387. Backbone.js powers Grove's web client together with <a href="http://handlebarsjs.com/">Handlebars.js templating</a>.
  2388. Updates to chat stream are pulled in realtime using long-polling.
  2389. </p>
  2390. <div style="text-align: center;">
  2391. <a href="http://grove.io">
  2392. <img src="docs/images/grove.png" alt="Grove.io" class="example_image" />
  2393. </a>
  2394. </div>
  2395. <h2 id="examples-kicksend">Kicksend</h2>
  2396. <p>
  2397. <a href="http://kicksend.com">Kicksend</a> is a real-time file sharing
  2398. platform that helps everyday people send and receive files of any size
  2399. with their friends and family. Kicksend's web application makes extensive
  2400. use of Backbone.js to model files, friends, lists and activity streams.
  2401. </p>
  2402. <div style="text-align: center;">
  2403. <a href="http://kicksend.com">
  2404. <img src="docs/images/kicksend.png" alt="Kicksend" class="example_image" />
  2405. </a>
  2406. </div>
  2407. <h2 id="examples-shortmail">Shortmail</h2>
  2408. <p>
  2409. <a href="http://410labs.com/">410 Labs</a> uses Backbone.js at
  2410. <a href="http://shortmail.com/">Shortmail.com</a> to build a
  2411. fast and responsive inbox, driven by the <a href="#Router">Router</a>.
  2412. Backbone works with a <a href="http://rubyonrails.org/">Rails</a> backend to provide inbox rendering, archiving,
  2413. replying, composing, and even a changes feed. Using Backbone's event-driven
  2414. model and pushing the rendering and interaction logic to the front-end
  2415. has not only simplified the view code, it has also drastically reduced the
  2416. load on Shortmail's servers.
  2417. </p>
  2418. <div style="text-align: center;">
  2419. <a href="http://shortmail.com">
  2420. <img src="docs/images/shortmail.png" alt="Shortmail" class="example_image" />
  2421. </a>
  2422. </div>
  2423. <h2 id="examples-battlefield">Battlefield Play4Free</h2>
  2424. <p>
  2425. <a href="http://battlefield.play4free.com/">Battlefield Play4Free</a> is
  2426. the latest free-to-play first person shooter from the same team that
  2427. created Battlefield Heroes. The in-game HTML5 front-end for makes heavy use of
  2428. Backbone's views, models and collections to help keep the code modular
  2429. and structured.
  2430. </p>
  2431. <div style="text-align: center;">
  2432. <a href="http://battlefield.play4free.com/">
  2433. <img src="docs/images/battlefield.png" alt="Battlefield Play4Free" class="example_image" />
  2434. </a>
  2435. </div>
  2436. <h2 id="examples-salon">Salon.io</h2>
  2437. <p>
  2438. <a href="http://salon.io">Salon.io</a> provides a space where photographers,
  2439. artists and designers freely arrange their visual art on virtual walls.
  2440. <a href="http://salon.io">Salon.io</a> runs on <a href="http://rubyonrails.org/">Rails</a>, but does not use
  2441. much of the traditional stack, as the entire frontend is designed as a
  2442. single page web app, using Backbone.js and
  2443. <a href="http://coffeescript.org">CoffeeScript</a>.
  2444. </p>
  2445. <div style="text-align: center;">
  2446. <a href="http://salon.io">
  2447. <img src="docs/images/salon.png" alt="Salon.io" class="example_image" />
  2448. </a>
  2449. </div>
  2450. <h2 id="examples-tilemill">TileMill</h2>
  2451. <p>
  2452. Our fellow
  2453. <a href="http://www.newschallenge.org/">Knight Foundation News Challenge</a>
  2454. winners, <a href="http://mapbox.com/">MapBox</a>, created an open-source
  2455. map design studio with Backbone.js:
  2456. <a href="http://mapbox.github.com/tilemill/">TileMill</a>.
  2457. TileMill lets you manage map layers based on shapefiles and rasters, and
  2458. edit their appearance directly in the browser with the
  2459. <a href="https://github.com/mapbox/carto">Carto styling language</a>.
  2460. Note that the gorgeous <a href="http://mapbox.com/">MapBox</a> homepage
  2461. is also a Backbone.js app.
  2462. </p>
  2463. <div style="text-align: center;">
  2464. <a href="http://mapbox.github.com/tilemill/">
  2465. <img src="docs/images/tilemill.png" alt="TileMill" class="example_image" />
  2466. </a>
  2467. </div>
  2468. <h2 id="examples-blossom">Blossom</h2>
  2469. <p>
  2470. <a href="http://blossom.io">Blossom</a> is a lightweight project management
  2471. tool for lean teams. Backbone.js is heavily used in combination with
  2472. <a href="http://coffeescript.org">CoffeeScript</a> to provide a smooth
  2473. interaction experience. The RESTful backend is built
  2474. with <a href="http://flask.pocoo.org/">Flask</a> on Google App Engine.
  2475. </p>
  2476. <div style="text-align: center;">
  2477. <a href="http://blossom.io">
  2478. <img src="docs/images/blossom.png" alt="Blossom" class="example_image" />
  2479. </a>
  2480. </div>
  2481. <h2 id="examples-animoto">Animoto</h2>
  2482. <p>
  2483. <a href="http://animoto.com">Animoto</a> is a web-based video creation
  2484. platform, where users can upload their own photos, video clips and music
  2485. and create beautifully orchestrated slideshows. The video editor app is
  2486. built with Backbone.js and <a href="http://jquery.com">jQuery</a> and interfaces with a <a href="http://rubyonrails.org/">Ruby on Rails</a>
  2487. backend. Backbone has provided structure which helps the Animoto team
  2488. iterate quickly on the codebase while reducing the risk of regressions.
  2489. </p>
  2490. <div style="text-align: center;">
  2491. <a href="http://www.animoto.com/">
  2492. <img src="docs/images/animoto.png" alt="Tzigla" class="Animoto Video Editor" />
  2493. </a>
  2494. </div>
  2495. <h2 id="examples-chaincal">ChainCal</h2>
  2496. <p>
  2497. <a href="http://chaincalapp.com/">ChainCal</a>
  2498. is an iPhone app that helps you to track your daily goals in a
  2499. minimalist, visual way. The app is written almost entirely in <a href="http://coffeescript.org/">CoffeeScript</a>,
  2500. Backbone handles the models, collections and views, and persistence is
  2501. done with a Backbone.sync localStorage adapter. Templates are written in
  2502. <a href="https://github.com/sstephenson/eco">Eco</a> and the app is packaged with <a href="http://brunch.io/">Brunch</a> and deployed with <a href="http://phonegap.com/">Phonegap</a>.
  2503. </p>
  2504. <div style="text-align: center;">
  2505. <a href="http://chaincalapp.com/">
  2506. <img src="docs/images/chaincal.png" alt="ChainCal" class="example_image" />
  2507. </a>
  2508. </div>
  2509. <h2 id="examples-attictv">AtticTV</h2>
  2510. <p>
  2511. <a href="http://attictv.com/">AtticTV</a> is MTV for the Youtube Generation:
  2512. kick back and relax while watching the best
  2513. music videos of your favorite genre. The videos are synced across the
  2514. world, so, you're never watching alone on AtticTV. AtticTV is served by
  2515. <a href="http://nodejs.org/">NodeJS</a> written in <a href="http://coffeescript.org/">CoffeeScript</a> with <a href="http://socket.io/">Socket.IO</a> as data transport. The
  2516. frontend is built with Backbone.js with pushstate support, <a href="http://jquery.com/">jQuery</a>, and
  2517. <a href="http://jade-lang.com/">Jade templates</a>.
  2518. </p>
  2519. <div style="text-align: center;">
  2520. <a href="http://attictv.com/">
  2521. <img src="docs/images/attictv.png" alt="AtticTV" class="example_image" />
  2522. </a>
  2523. </div>
  2524. <h2 id="examples-decide">Decide</h2>
  2525. <p>
  2526. <a href="http://decide.com">Decide.com</a> helps people decide when to buy
  2527. consumer electronics. It relies heavily on Backbone.js to render and
  2528. update its Search Results Page. An "infinite scroll" feature takes
  2529. advantage of a SearchResults model containing a collection of
  2530. Product models to fetch more results and render them on the fly
  2531. with <a href="http://mustache.github.com">Mustache</a>. A SearchController keeps everything in sync and
  2532. maintains page state in the URL. Backbone also powers the user
  2533. accounts and settings management.
  2534. </p>
  2535. <div style="text-align: center;">
  2536. <a href="http://decide.com">
  2537. <img src="docs/images/decide.png" alt="Decide" class="example_image" />
  2538. </a>
  2539. </div>
  2540. <h2 id="examples-editd">EDITD</h2>
  2541. <p>
  2542. <a href="http://editd.com">EDITD</a> aims to disrupt the fashion
  2543. industry with big data. The next generation of their web application
  2544. is based on a custom JavaScript framework that builds on top of
  2545. Backbone. The back end is
  2546. <a href="https://www.djangoproject.com/">Django</a> +
  2547. <a href="http://www.elasticsearch.org/">Elastic Search</a>,
  2548. <a href="http://handlebarsjs.com/">Handlebars.js</a> is used for templating,
  2549. <a href="http://code.google.com/p/js-test-driver/">jsTestDriver</a> for testing, and
  2550. <a href="http://jashkenas.github.com/docco/">Docco</a> for quick documentation.
  2551. </p>
  2552. <div style="text-align: center;">
  2553. <a href="http://editd.com">
  2554. <img src="docs/images/editd.png" alt="EDITD" class="example_image" />
  2555. </a>
  2556. </div>
  2557. <h2 id="examples-trello">Trello</h2>
  2558. <p>
  2559. <a href="http://trello.com">Trello</a> is a collaboration tool that
  2560. organizes your projects into boards. A Trello board holds many lists of
  2561. cards, which can contain checklists, files and conversations, and may be
  2562. voted on and organized with labels. Updates on the board happen in
  2563. real time. The site was built ground up using Backbone.js for all the
  2564. models, views, and routes.
  2565. </p>
  2566. <div style="text-align: center;">
  2567. <a href="http://trello.com">
  2568. <img src="docs/images/trello.png" alt="Trello" class="example_image" />
  2569. </a>
  2570. </div>
  2571. <h2 id="examples-ducksboard">Ducksboard</h2>
  2572. <p>
  2573. <a href="http://ducksboard.com/">Ducksboard</a> is an online dashboard
  2574. for your SaaS and business metrics, built with
  2575. <a href="http://twistedmatrix.com/">Twisted</a> and
  2576. <a href="http://www.djangoproject.com/">Django</a> and using WebSockets.
  2577. It can fetch data from popular providers or accept input through
  2578. a simple API.
  2579. Backbone is used throughout Ducksboard's interface, every widget,
  2580. dashboard and SaaS account is a Backbone model with several views
  2581. (data display, configuration view). A
  2582. <a href="https://public.ducksboard.com/BFVzKVPeOoWRsL0VZ8MZ/">live demo</a>
  2583. is available.
  2584. </p>
  2585. <div style="text-align: center;">
  2586. <a href="http://ducksboard.com/">
  2587. <img src="docs/images/ducksboard.png" alt="Ducksboard" class="example_image" />
  2588. </a>
  2589. </div>
  2590. <h2 id="examples-quietwrite">QuietWrite</h2>
  2591. <p>
  2592. <a href="http://www.twitter.com/jamesjyu">James Yu</a> used Backbone.js to
  2593. create <a href="http://www.quietwrite.com/">QuietWrite</a>, an app
  2594. that gives writers a clean and quiet interface to concentrate on the text itself.
  2595. The editor relies on Backbone to persist document data to the server. He
  2596. followed up with a Backbone.js + <a href="http://rubyonrails.org/">Rails</a> tutorial that describes how to implement
  2597. <a href="http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/">CloudEdit, a simple document editing app</a>.
  2598. </p>
  2599. <div style="text-align: center;">
  2600. <a href="http://www.quietwrite.com/">
  2601. <img src="docs/images/quietwrite.png" alt="QuietWrite" class="example_image" />
  2602. </a>
  2603. </div>
  2604. <h2 id="examples-tzigla">Tzigla</h2>
  2605. <p>
  2606. <a href="http://twitter.com/evilchelu">Cristi Balan</a> and
  2607. <a href="http://dira.ro">Irina Dumitrascu</a> created
  2608. <a href="http://tzigla.com">Tzigla</a>, a collaborative drawing
  2609. application where artists make tiles that connect to each other to
  2610. create <a href="http://tzigla.com/boards/1">surreal drawings</a>.
  2611. Backbone models help organize the code, routers provide
  2612. <a href="http://tzigla.com/boards/1#!/tiles/2-2">bookmarkable deep links</a>,
  2613. and the views are rendered with
  2614. <a href="https://github.com/creationix/haml-js">haml.js</a> and
  2615. <a href="http://zeptojs.com/">Zepto</a>.
  2616. Tzigla is written in Ruby (<a href="http://rubyonrails.org/">Rails</a>) on the backend, and
  2617. <a href="http://coffeescript.org">CoffeeScript</a> on the frontend, with
  2618. <a href="http://documentcloud.github.com/jammit/">Jammit</a>
  2619. prepackaging the static assets.
  2620. </p>
  2621. <div style="text-align: center;">
  2622. <a href="http://www.tzigla.com/">
  2623. <img src="docs/images/tzigla.png" alt="Tzigla" class="example_image" />
  2624. </a>
  2625. </div>
  2626. <h2 id="faq">F.A.Q.</h2>
  2627. <p id="FAQ-events">
  2628. <b class="header">Catalog of Events</b>
  2629. <br />
  2630. Here's a list of all of the built-in events that Backbone.js can fire.
  2631. You're also free to trigger your own events on Models and Views as you
  2632. see fit.
  2633. </p>
  2634. <ul class="small">
  2635. <li><b>"add"</b> (model, collection) &mdash; when a model is added to a collection. </li>
  2636. <li><b>"remove"</b> (model, collection) &mdash; when a model is removed from a collection. </li>
  2637. <li><b>"reset"</b> (collection) &mdash; when the collection's entire contents have been replaced. </li>
  2638. <li><b>"change"</b> (model, options) &mdash; when a model's attributes have changed. </li>
  2639. <li><b>"change:[attribute]"</b> (model, value, options) &mdash; when a specific attribute has been updated. </li>
  2640. <li><b>"destroy"</b> (model, collection) &mdash; when a model is <a href="#Model-destroy">destroyed</a>. </li>
  2641. <li><b>"sync"</b> (model, collection) &mdash; triggers whenever a model has been successfully synced to the server. </li>
  2642. <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>
  2643. <li><b>"route:[name]"</b> (router) &mdash; when one of a router's routes has matched. </li>
  2644. <li><b>"all"</b> &mdash; this special event fires for <i>any</i> triggered event, passing the event name as the first argument. </li>
  2645. </ul>
  2646. <p id="FAQ-tim-toady">
  2647. <b class="header">There's More Than One Way To Do It</b>
  2648. <br />
  2649. It's common for folks just getting started to treat the examples listed
  2650. on this page as some sort of gospel truth. In fact, Backbone.js is intended
  2651. to be fairly agnostic about many common patterns in client-side code.
  2652. For example...
  2653. </p>
  2654. <p>
  2655. <b>References between Models and Views</b> can be handled several ways.
  2656. Some people like to have direct pointers, where views correspond 1:1 with
  2657. models (<tt>model.view</tt> and <tt>view.model</tt>). Others prefer to have intermediate
  2658. "controller" objects that orchestrate the creation and organization of
  2659. views into a hierarchy. Others still prefer the evented approach, and always
  2660. fire events instead of calling methods directly. All of these styles work well.
  2661. </p>
  2662. <p>
  2663. <b>Batch operations</b> on Models are common, but often best handled differently
  2664. depending on your server-side setup. Some folks don't mind making individual
  2665. Ajax requests. Others create explicit resources for RESTful batch operations:
  2666. <tt>/notes/batch/destroy?ids=1,2,3,4</tt>. Others tunnel REST over JSON, with the
  2667. creation of "changeset" requests:
  2668. </p>
  2669. <pre>
  2670. {
  2671. "create": [array of models to create]
  2672. "update": [array of models to update]
  2673. "destroy": [array of model ids to destroy]
  2674. }
  2675. </pre>
  2676. <p>
  2677. <b>Feel free to define your own events.</b> <a href="#Events">Backbone.Events</a>
  2678. is designed so that you can mix it in to any JavaScript object or prototype.
  2679. Since you can use any string as an event, it's often handy to bind
  2680. and trigger your own custom events: <tt>model.on("selected:true")</tt> or
  2681. <tt>model.on("editing")</tt>
  2682. </p>
  2683. <p>
  2684. <b>Render the UI</b> as you see fit. Backbone is agnostic as to whether you
  2685. use <a href="http://documentcloud.github.com/underscore/#template">Underscore templates</a>,
  2686. <a href="https://github.com/janl/mustache.js">Mustache.js</a>, direct DOM
  2687. manipulation, server-side rendered snippets of HTML, or
  2688. <a href="http://jqueryui.com/">jQuery UI</a> in your <tt>render</tt> function.
  2689. Sometimes you'll create a view for each model ... sometimes you'll have a
  2690. view that renders thousands of models at once, in a tight loop. Both can be
  2691. appropriate in the same app, depending on the quantity of data involved,
  2692. and the complexity of the UI.
  2693. </p>
  2694. <p id="FAQ-nested">
  2695. <b class="header">Nested Models &amp; Collections</b>
  2696. <br />
  2697. It's common to nest collections inside of models with Backbone. For example,
  2698. consider a <tt>Mailbox</tt> model that contains many <tt>Message</tt> models.
  2699. One nice pattern for handling this is have a <tt>this.messages</tt> collection
  2700. for each mailbox, enabling the lazy-loading of messages, when the mailbox
  2701. is first opened ... perhaps with <tt>MessageList</tt> views listening for
  2702. <tt>"add"</tt> and <tt>"remove"</tt> events.
  2703. </p>
  2704. <pre>
  2705. var Mailbox = Backbone.Model.extend({
  2706. initialize: function() {
  2707. this.messages = new Messages;
  2708. this.messages.url = '/mailbox/' + this.id + '/messages';
  2709. this.messages.on("reset", this.updateCounts);
  2710. },
  2711. ...
  2712. });
  2713. var Inbox = new Mailbox;
  2714. // And then, when the Inbox is opened:
  2715. Inbox.messages.fetch();
  2716. </pre>
  2717. <p>
  2718. If you're looking for something more opinionated, there are a number of
  2719. Backbone plugins that add sophisticated associations among models,
  2720. <a href="https://github.com/documentcloud/backbone/wiki/Extensions%2C-Plugins%2C-Resources">available on the wiki</a>.
  2721. </p>
  2722. <p>
  2723. Backbone doesn't include direct support for nested models and collections
  2724. or "has many" associations because there are a number
  2725. of good patterns for modeling structured data on the client side, and
  2726. <i>Backbone should provide the foundation for implementing any of them.</i>
  2727. You may want to&hellip;
  2728. </p>
  2729. <ul>
  2730. <li>
  2731. Mirror an SQL database's structure, or the structure of a NoSQL database.
  2732. </li>
  2733. <li>
  2734. Use models with arrays of "foreign key" ids, and join to top level
  2735. collections (a-la tables).
  2736. </li>
  2737. <li>
  2738. For associations that are numerous, use a range of ids instead of an
  2739. explicit list.
  2740. </li>
  2741. <li>
  2742. Avoid ids, and use direct references, creating a partial object graph
  2743. representing your data set.
  2744. </li>
  2745. <li>
  2746. Lazily load joined models from the server, or lazily deserialize nested
  2747. models from JSON documents.
  2748. </li>
  2749. </ul>
  2750. <p id="FAQ-bootstrap">
  2751. <b class="header">Loading Bootstrapped Models</b>
  2752. <br />
  2753. When your app first loads, it's common to have a set of initial models that
  2754. you know you're going to need, in order to render the page. Instead of
  2755. firing an extra AJAX request to <a href="#Collection-fetch">fetch</a> them,
  2756. a nicer pattern is to have their data already bootstrapped into the page.
  2757. You can then use <a href="#Collection-reset">reset</a> to populate your
  2758. collections with the initial data. At DocumentCloud, in the
  2759. <a href="http://en.wikipedia.org/wiki/ERuby">ERB</a> template for the
  2760. workspace, we do something along these lines:
  2761. </p>
  2762. <pre>
  2763. &lt;script&gt;
  2764. var Accounts = new Backbone.Collection;
  2765. Accounts.reset(&lt;%= @accounts.to_json %&gt;);
  2766. var Projects = new Backbone.Collection;
  2767. Projects.reset(&lt;%= @projects.to_json(:collaborators => true) %&gt;);
  2768. &lt;/script&gt;
  2769. </pre>
  2770. <p>You have to <a href="http://mathiasbynens.be/notes/etago">escape</a>
  2771. <tt>&lt;/</tt> within the JSON string, to prevent javascript injection
  2772. attacks.
  2773. <p id="FAQ-extending">
  2774. <b class="header">Extending Backbone</b>
  2775. <br />
  2776. Many JavaScript libraries are meant to be insular and self-enclosed,
  2777. where you interact with them by calling their public API, but never peek
  2778. inside at the guts. Backbone.js is <i>not</i> that kind of library.
  2779. </p>
  2780. <p>
  2781. Because it serves as a foundation for your application, you're meant to
  2782. extend and enhance it in the ways you see fit &mdash; the entire source
  2783. code is <a href="docs/backbone.html">annotated</a> to make this easier
  2784. for you. You'll find that there's very little there apart from core
  2785. functions, and most of those can be overriden or augmented should you find
  2786. the need. If you catch yourself adding methods to <tt>Backbone.Model.prototype</tt>,
  2787. or creating your own base subclass, don't worry &mdash; that's how things are
  2788. supposed to work.
  2789. </p>
  2790. <p id="FAQ-mvc">
  2791. <b class="header">How does Backbone relate to "traditional" MVC?</b>
  2792. <br />
  2793. Different implementations of the
  2794. <a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
  2795. pattern tend to disagree about the definition of a controller. If it helps any, in
  2796. Backbone, the <a href="#View">View</a> class can also be thought of as a
  2797. kind of controller, dispatching events that originate from the UI, with
  2798. the HTML template serving as the true view. We call it a View because it
  2799. represents a logical chunk of UI, responsible for the contents of a single
  2800. DOM element.
  2801. </p>
  2802. <p>
  2803. Comparing the overall structure of Backbone to a server-side MVC framework
  2804. like <b>Rails</b>, the pieces line up like so:
  2805. </p>
  2806. <ul>
  2807. <li>
  2808. <b>Backbone.Model</b> &ndash; Like a Rails model minus the class
  2809. methods. Wraps a row of data in business logic.
  2810. </li>
  2811. <li>
  2812. <b>Backbone.Collection</b> &ndash; A group of models on the client-side,
  2813. with sorting/filtering/aggregation logic.
  2814. </li>
  2815. <li>
  2816. <b>Backbone.Router</b> &ndash; Rails <tt>routes.rb</tt> + Rails controller
  2817. actions. Maps URLs to functions.
  2818. </li>
  2819. <li>
  2820. <b>Backbone.View</b> &ndash; A logical, re-usable piece of UI. Often,
  2821. but not always, associated with a model.
  2822. </li>
  2823. <li>
  2824. <b>Client-side Templates</b> &ndash; Rails <tt>.html.erb</tt> views,
  2825. rendering a chunk of HTML.
  2826. </li>
  2827. </ul>
  2828. <p id="FAQ-this">
  2829. <b class="header">Binding "this"</b>
  2830. <br />
  2831. Perhaps the single most common JavaScript "gotcha" is the fact that when
  2832. you pass a function as a callback, its value for <tt>this</tt> is lost. With
  2833. Backbone, when dealing with <a href="#Events">events</a> and callbacks,
  2834. you'll often find it useful to rely on
  2835. <a href="http://documentcloud.github.com/underscore/#bind">_.bind</a> and
  2836. <a href="http://documentcloud.github.com/underscore/#bindAll">_.bindAll</a>
  2837. from Underscore.js.
  2838. </p>
  2839. <p>
  2840. When binding callbacks to Backbone events, you can choose to pass an optional
  2841. third argument to specify the <tt>this</tt> that will be used when the
  2842. callback is later invoked:
  2843. </p>
  2844. <pre>
  2845. var MessageList = Backbone.View.extend({
  2846. initialize: function() {
  2847. var messages = this.collection;
  2848. messages.on("reset", this.render, this);
  2849. messages.on("add", this.addMessage, this);
  2850. messages.on("remove", this.removeMessage, this);
  2851. }
  2852. });
  2853. // Later, in the app...
  2854. Inbox.messages.add(newMessage);
  2855. </pre>
  2856. <p id="FAQ-rails">
  2857. <b class="header">Working with Rails</b>
  2858. <br />
  2859. Backbone.js was originally extracted from
  2860. <a href="http://www.documentcloud.org">a Rails application</a>; getting
  2861. your client-side (Backbone) Models to sync correctly with your server-side
  2862. (Rails) Models is painless, but there are still a few things to be aware of.
  2863. </p>
  2864. <p>
  2865. By default, Rails adds an extra layer of wrapping around the JSON representation
  2866. of models. You can disable this wrapping by setting:
  2867. </p>
  2868. <pre>
  2869. ActiveRecord::Base.include_root_in_json = false
  2870. </pre>
  2871. <p>
  2872. ... in your configuration. Otherwise, override
  2873. <a href="#Model-parse">parse</a> to pull model attributes out of the
  2874. wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations
  2875. of models, where by default Rails expects namespaced attributes. You can
  2876. have your controllers filter attributes directly from <tt>params</tt>, or
  2877. you can override <a href="#Model-toJSON">toJSON</a> in Backbone to add
  2878. the extra wrapping Rails expects.
  2879. </p>
  2880. <h2 id="changelog">Change Log</h2>
  2881. <b class="header">0.9.2</b> &mdash; <small><i>March 21, 2012</i></small> &mdash; <a href="https://github.com/documentcloud/backbone/compare/0.9.1...0.9.2">Diff</a><br />
  2882. <ul style="margin-top: 5px;">
  2883. <li>
  2884. Instead of throwing an error when adding duplicate models to a collection,
  2885. Backbone will now silently skip them instead.
  2886. </li>
  2887. <li>
  2888. Added <a href="#Collection-push">push</a>,
  2889. <a href="#Collection-pop">pop</a>,
  2890. <a href="#Collection-unshift">unshift</a>, and
  2891. <a href="#Collection-shift">shift</a> to collections.
  2892. </li>
  2893. <li>
  2894. A model's <a href="#Model-changed">changed</a> hash is now exposed for
  2895. easy reading of the changed attribute delta, since the model's last
  2896. <tt>"change"</tt> event.
  2897. </li>
  2898. <li>
  2899. Added <a href="#Collection-where">where</a> to collections for simple
  2900. filtering.
  2901. </li>
  2902. <li>
  2903. You can now use a single <a href="#Events-off">off</a> call
  2904. to remove all callbacks bound to a specific object.
  2905. </li>
  2906. <li>
  2907. Bug fixes for nested individual change events, some of which may be
  2908. "silent".
  2909. </li>
  2910. <li>
  2911. Bug fixes for URL encoding in <tt>location.hash</tt> fragments.
  2912. </li>
  2913. <li>
  2914. Bug fix for client-side validation in advance of a <tt>save</tt> call
  2915. with <tt>{wait: true}</tt>.
  2916. </li>
  2917. <li>
  2918. Updated / refreshed the example
  2919. <a href="examples/todos/index.html">Todo List</a> app.
  2920. </li>
  2921. </ul>
  2922. <b class="header">0.9.1</b> &mdash; <small><i>Feb. 2, 2012</i></small> &mdash; <a href="https://github.com/documentcloud/backbone/compare/0.9.0...0.9.1">Diff</a><br />
  2923. <ul style="margin-top: 5px;">
  2924. <li>
  2925. Reverted to 0.5.3-esque behavior for validating models. Silent changes
  2926. no longer trigger validation (making it easier to work with forms).
  2927. Added an <tt>isValid</tt> function that you can use to check if a model
  2928. is currently in a valid state.
  2929. </li>
  2930. <li>
  2931. If you have multiple versions of jQuery on the page, you can now tell
  2932. Backbone which one to use with <tt>Backbone.setDomLibrary</tt>.
  2933. </li>
  2934. <li>
  2935. Fixes regressions in <b>0.9.0</b> for routing with "root", saving with
  2936. both "wait" and "validate", and the order of nested "change" events.
  2937. </li>
  2938. </ul>
  2939. <b class="header">0.9.0</b> &mdash; <small><i>Jan. 30, 2012</i></small> &mdash; <a href="https://github.com/documentcloud/backbone/compare/0.5.3...0.9.0">Diff</a><br />
  2940. <ul style="margin-top: 5px;">
  2941. <li>
  2942. Creating and destroying models with <tt>create</tt> and <tt>destroy</tt>
  2943. are now optimistic by default. Pass <tt>{wait: true}</tt> as an option
  2944. if you'd like them to wait for a successful server response to proceed.
  2945. </li>
  2946. <li>
  2947. Two new properties on views: <tt>$el</tt> &mdash; a cached jQuery (or Zepto)
  2948. reference to the view's element, and <tt>setElement</tt>, which should
  2949. be used instead of manually setting a view's <tt>el</tt>. It will
  2950. both set <tt>view.el</tt> and <tt>view.$el</tt> correctly, as well as
  2951. re-delegating events on the new DOM element.
  2952. </li>
  2953. <li>
  2954. You can now bind and trigger multiple spaced-delimited events at once.
  2955. For example: <tt>model.on("change:name change:age", ...)</tt>
  2956. </li>
  2957. <li>
  2958. When you don't know the key in advance, you may now call
  2959. <tt>model.set(key, value)</tt> as well as <tt>save</tt>.
  2960. </li>
  2961. <li>
  2962. Multiple models with the same <tt>id</tt> are no longer allowed in a
  2963. single collection.
  2964. </li>
  2965. <li>
  2966. Added a <tt>"sync"</tt> event, which triggers whenever a model's state
  2967. has been successfully synced with the server (create, save, destroy).
  2968. </li>
  2969. <li>
  2970. <tt>bind</tt> and <tt>unbind</tt> have been renamed to <tt>on</tt>
  2971. and <tt>off</tt> for clarity, following jQuery's lead.
  2972. The old names are also still supported.
  2973. </li>
  2974. <li>
  2975. A Backbone collection's <tt>comparator</tt> function may now behave
  2976. either like a <a href="http://underscorejs.org/#sortBy">sortBy</a>
  2977. (pass a function that takes a single argument),
  2978. or like a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort">sort</a>
  2979. (pass a comparator function that expects two arguments). The comparator
  2980. function is also now bound by default to the collection &mdash; so you
  2981. can refer to <tt>this</tt> within it.
  2982. </li>
  2983. <li>
  2984. A view's <tt>events</tt> hash may now also contain direct function
  2985. values as well as the string names of existing view methods.
  2986. </li>
  2987. <li>
  2988. Validation has gotten an overhaul &mdash; a model's <tt>validate</tt> function
  2989. will now be run even for silent changes, and you can no longer create
  2990. a model in an initially invalid state.
  2991. </li>
  2992. <li>
  2993. Added <tt>shuffle</tt> and <tt>initial</tt> to collections, proxied
  2994. from Underscore.
  2995. </li>
  2996. <li>
  2997. <tt>Model#urlRoot</tt> may now be defined as a function as well as a
  2998. value.
  2999. </li>
  3000. <li>
  3001. <tt>View#attributes</tt> may now be defined as a function as well as a
  3002. value.
  3003. </li>
  3004. <li>
  3005. Calling <tt>fetch</tt> on a collection will now cause all fetched JSON
  3006. to be run through the collection's model's <tt>parse</tt> function, if
  3007. one is defined.
  3008. </li>
  3009. <li>
  3010. You may now tell a router to <tt>navigate(fragment, {replace: true})</tt>,
  3011. which will either use <tt>history.replaceState</tt> or
  3012. <tt>location.hash.replace</tt>, in order to change the URL without adding
  3013. a history entry.
  3014. </li>
  3015. <li>
  3016. Within a collection's <tt>add</tt> and <tt>remove</tt> events, the index
  3017. of the model being added or removed is now available as <tt>options.index</tt>.
  3018. </li>
  3019. <li>
  3020. Added an <tt>undelegateEvents</tt> to views, allowing you to manually
  3021. remove all configured event delegations.
  3022. </li>
  3023. <li>
  3024. Although you shouldn't be writing your routes with them in any case &mdash;
  3025. leading slashes (<tt>/</tt>) are now stripped from routes.
  3026. </li>
  3027. <li>
  3028. Calling <tt>clone</tt> on a model now only passes the attributes
  3029. for duplication, not a reference to the model itself.
  3030. </li>
  3031. </ul>
  3032. <p>
  3033. <b class="header">0.5.3</b> &mdash; <small><i>August 9, 2011</i></small><br />
  3034. A View's <tt>events</tt> property may now be defined as a function, as well
  3035. as an object literal, making it easier to programmatically define and inherit
  3036. events. <tt>groupBy</tt> is now proxied from Underscore as a method on Collections.
  3037. If the server has already rendered everything on page load, pass
  3038. <tt>Backbone.history.start({silent: true})</tt> to prevent the initial route
  3039. from triggering. Bugfix for pushState with encoded URLs.
  3040. </p>
  3041. <p>
  3042. <b class="header">0.5.2</b> &mdash; <small><i>July 26, 2011</i></small><br />
  3043. The <tt>bind</tt> function, can now take an optional third argument, to specify
  3044. the <tt>this</tt> of the callback function.
  3045. Multiple models with the same <tt>id</tt> are now allowed in a collection.
  3046. Fixed a bug where calling <tt>.fetch(jQueryOptions)</tt> could cause an
  3047. incorrect URL to be serialized.
  3048. Fixed a brief extra route fire before redirect, when degrading from
  3049. <tt>pushState</tt>.
  3050. </p>
  3051. <p>
  3052. <b class="header">0.5.1</b> &mdash; <small><i>July 5, 2011</i></small><br />
  3053. Cleanups from the 0.5.0 release, to wit: improved transparent upgrades from
  3054. hash-based URLs to pushState, and vice-versa. Fixed inconsistency with
  3055. non-modified attributes being passed to <tt>Model#initialize</tt>. Reverted
  3056. a <b>0.5.0</b> change that would strip leading hashbangs from routes.
  3057. Added <tt>contains</tt> as an alias for <tt>includes</tt>.
  3058. </p>
  3059. <p>
  3060. <b class="header">0.5.0</b> &mdash; <small><i>July 1, 2011</i></small><br />
  3061. A large number of tiny tweaks and micro bugfixes, best viewed by looking
  3062. at <a href="https://github.com/documentcloud/backbone/compare/0.3.3...0.5.0">the commit diff</a>.
  3063. HTML5 <tt>pushState</tt> support, enabled by opting-in with:
  3064. <tt>Backbone.history.start({pushState: true})</tt>.
  3065. <tt>Controller</tt> was renamed to <tt>Router</tt>, for clarity.
  3066. <tt>Collection#refresh</tt> was renamed to <tt>Collection#reset</tt> to emphasize
  3067. its ability to both reset the collection with new models, as well as empty
  3068. out the collection when used with no parameters.
  3069. <tt>saveLocation</tt> was replaced with <tt>navigate</tt>.
  3070. RESTful persistence methods (save, fetch, etc.) now return the jQuery deferred
  3071. object for further success/error chaining and general convenience.
  3072. Improved XSS escaping for <tt>Model#escape</tt>.
  3073. Added a <tt>urlRoot</tt> option to allow specifying RESTful urls without
  3074. the use of a collection.
  3075. An error is thrown if <tt>Backbone.history.start</tt> is called multiple times.
  3076. <tt>Collection#create</tt> now validates before initializing the new model.
  3077. <tt>view.el</tt> can now be a jQuery string lookup.
  3078. Backbone Views can now also take an <tt>attributes</tt> parameter.
  3079. <tt>Model#defaults</tt> can now be a function as well as a literal attributes
  3080. object.
  3081. </p>
  3082. <p>
  3083. <b class="header">0.3.3</b> &mdash; <small><i>Dec 1, 2010</i></small><br />
  3084. Backbone.js now supports <a href="http://zeptojs.com">Zepto</a>, alongside
  3085. jQuery, as a framework for DOM manipulation and Ajax support.
  3086. Implemented <a href="#Model-escape">Model#escape</a>, to efficiently handle
  3087. attributes intended for HTML interpolation. When trying to persist a model,
  3088. failed requests will now trigger an <tt>"error"</tt> event. The
  3089. ubiquitous <tt>options</tt> argument is now passed as the final argument
  3090. to all <tt>"change"</tt> events.
  3091. </p>
  3092. <p>
  3093. <b class="header">0.3.2</b> &mdash; <small><i>Nov 23, 2010</i></small><br />
  3094. Bugfix for IE7 + iframe-based "hashchange" events. <tt>sync</tt> may now be
  3095. overridden on a per-model, or per-collection basis. Fixed recursion error
  3096. when calling <tt>save</tt> with no changed attributes, within a
  3097. <tt>"change"</tt> event.
  3098. </p>
  3099. <p>
  3100. <b class="header">0.3.1</b> &mdash; <small><i>Nov 15, 2010</i></small><br />
  3101. All <tt>"add"</tt> and <tt>"remove"</tt> events are now sent through the
  3102. model, so that views can listen for them without having to know about the
  3103. collection. Added a <tt>remove</tt> method to <a href="#View">Backbone.View</a>.
  3104. <tt>toJSON</tt> is no longer called at all for <tt>'read'</tt> and <tt>'delete'</tt> requests.
  3105. Backbone routes are now able to load empty URL fragments.
  3106. </p>
  3107. <p>
  3108. <b class="header">0.3.0</b> &mdash; <small><i>Nov 9, 2010</i></small><br />
  3109. Backbone now has <a href="#Controller">Controllers</a> and
  3110. <a href="#History">History</a>, for doing client-side routing based on
  3111. URL fragments.
  3112. Added <tt>emulateHTTP</tt> to provide support for legacy servers that don't
  3113. do <tt>PUT</tt> and <tt>DELETE</tt>.
  3114. Added <tt>emulateJSON</tt> for servers that can't accept <tt>application/json</tt>
  3115. encoded requests.
  3116. Added <a href="#Model-clear">Model#clear</a>, which removes all attributes
  3117. from a model.
  3118. All Backbone classes may now be seamlessly inherited by CoffeeScript classes.
  3119. </p>
  3120. <p>
  3121. <b class="header">0.2.0</b> &mdash; <small><i>Oct 25, 2010</i></small><br />
  3122. Instead of requiring server responses to be namespaced under a <tt>model</tt>
  3123. key, now you can define your own <a href="#Model-parse">parse</a> method
  3124. to convert responses into attributes for Models and Collections.
  3125. The old <tt>handleEvents</tt> function is now named
  3126. <a href="#View-delegateEvents">delegateEvents</a>, and is automatically
  3127. called as part of the View's constructor.
  3128. Added a <a href="#Collection-toJSON">toJSON</a> function to Collections.
  3129. Added <a href="#Collection-chain">Underscore's chain</a> to Collections.
  3130. </p>
  3131. <p>
  3132. <b class="header">0.1.2</b> &mdash; <small><i>Oct 19, 2010</i></small><br />
  3133. Added a <a href="#Model-fetch">Model#fetch</a> method for refreshing the
  3134. attributes of single model from the server.
  3135. An <tt>error</tt> callback may now be passed to <tt>set</tt> and <tt>save</tt>
  3136. as an option, which will be invoked if validation fails, overriding the
  3137. <tt>"error"</tt> event.
  3138. You can now tell backbone to use the <tt>_method</tt> hack instead of HTTP
  3139. methods by setting <tt>Backbone.emulateHTTP = true</tt>.
  3140. Existing Model and Collection data is no longer sent up unnecessarily with
  3141. <tt>GET</tt> and <tt>DELETE</tt> requests. Added a <tt>rake lint</tt> task.
  3142. Backbone is now published as an <a href="http://npmjs.org">NPM</a> module.
  3143. </p>
  3144. <p>
  3145. <b class="header">0.1.1</b> &mdash; <small><i>Oct 14, 2010</i></small><br />
  3146. Added a convention for <tt>initialize</tt> functions to be called
  3147. upon instance construction, if defined. Documentation tweaks.
  3148. </p>
  3149. <p>
  3150. <b class="header">0.1.0</b> &mdash; <small><i>Oct 13, 2010</i></small><br />
  3151. Initial Backbone release.
  3152. </p>
  3153. <p>
  3154. <br />
  3155. <a href="http://documentcloud.org/" title="A DocumentCloud Project" style="background:none;">
  3156. <img src="http://jashkenas.s3.amazonaws.com/images/a_documentcloud_project.png" alt="A DocumentCloud Project" style="position:relative;left:-10px;" />
  3157. </a>
  3158. </p>
  3159. </div>
  3160. <script src="test/vendor/underscore-1.3.1.js"></script>
  3161. <script src="test/vendor/jquery-1.7.1.js"></script>
  3162. <script src="test/vendor/json2.js"></script>
  3163. <script src="backbone.js"></script>
  3164. <script>
  3165. // Set up the "play" buttons for each runnable code example.
  3166. $(function() {
  3167. $('.runnable').each(function() {
  3168. var code = this;
  3169. var button = '<div class="run" title="Run"></div>';
  3170. $(button).insertBefore(code).bind('click', function(){
  3171. eval($(code).text());
  3172. });
  3173. });
  3174. });
  3175. </script>
  3176. </body>
  3177. </html>