PageRenderTime 97ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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