PageRenderTime 45ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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