PageRenderTime 79ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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