PageRenderTime 85ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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