PageRenderTime 99ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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