PageRenderTime 89ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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