PageRenderTime 107ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/index.html

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