PageRenderTime 94ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

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