PageRenderTime 99ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 1ms

/bower_components/backbone/index.html

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