PageRenderTime 91ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/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