PageRenderTime 92ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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