PageRenderTime 76ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/ender/test/node_modules/backbone/index.html

http://github.com/projexsys/Jolt
HTML | 1734 lines | 1514 code | 220 blank | 0 comment | 0 complexity | 91179267c4839a9621bcf74f1406e6a1 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, Apache-2.0, MIT, BSD-3-Clause
  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. <link rel="icon" href="docs/images/favicon.ico" />
  7. <title>Backbone.js</title>
  8. <style>
  9. body {
  10. font-size: 14px;
  11. line-height: 22px;
  12. font-family: Helvetica Neue, Helvetica, Arial;
  13. background: #f4f4f4 url(docs/images/background.png);
  14. }
  15. .interface {
  16. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  17. }
  18. div#sidebar {
  19. background: #fff;
  20. position: fixed;
  21. top: 0; left: 0; bottom: 0;
  22. width: 200px;
  23. overflow-y: auto;
  24. overflow-x: hidden;
  25. padding: 15px 0 30px 30px;
  26. border-right: 1px solid #bbb;
  27. box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  28. }
  29. a.toc_title, a.toc_title:visited {
  30. display: block;
  31. color: black;
  32. font-weight: bold;
  33. margin-top: 15px;
  34. }
  35. a.toc_title:hover {
  36. text-decoration: underline;
  37. }
  38. #sidebar .version {
  39. font-size: 10px;
  40. font-weight: normal;
  41. }
  42. ul.toc_section {
  43. font-size: 11px;
  44. line-height: 14px;
  45. margin: 5px 0 0 0;
  46. padding-left: 0px;
  47. list-style-type: none;
  48. font-family: Lucida Grande;
  49. }
  50. .toc_section li {
  51. cursor: pointer;
  52. margin: 0 0 3px 0;
  53. }
  54. .toc_section li a {
  55. text-decoration: none;
  56. color: black;
  57. }
  58. .toc_section li a:hover {
  59. text-decoration: underline;
  60. }
  61. div.container {
  62. position: relative;
  63. width: 550px;
  64. margin: 40px 0 50px 260px;
  65. }
  66. div.run {
  67. position: absolute;
  68. right: 15px;
  69. width: 26px; height: 18px;
  70. background: url('docs/images/arrows.png') no-repeat -26px 0;
  71. }
  72. div.run:active {
  73. background-position: -51px 0;
  74. }
  75. p, div.container ul {
  76. margin: 25px 0;
  77. width: 550px;
  78. }
  79. p.warning {
  80. font-size: 12px;
  81. line-height: 18px;
  82. font-style: italic;
  83. }
  84. div.container ul {
  85. list-style: circle;
  86. padding-left: 15px;
  87. font-size: 13px;
  88. line-height: 18px;
  89. }
  90. div.container ul li {
  91. margin-bottom: 10px;
  92. }
  93. div.container ul.small {
  94. font-size: 12px;
  95. }
  96. a, a:visited {
  97. color: #444;
  98. }
  99. a:active, a:hover {
  100. color: #000;
  101. }
  102. a.punch {
  103. display: inline-block;
  104. background: #4162a8;
  105. border-top: 1px solid #38538c;
  106. border-right: 1px solid #1f2d4d;
  107. border-bottom: 1px solid #151e33;
  108. border-left: 1px solid #1f2d4d;
  109. -webkit-border-radius: 4px;
  110. -moz-border-radius: 4px;
  111. -ms-border-radius: 4px;
  112. -o-border-radius: 4px;
  113. border-radius: 4px;
  114. -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  115. -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  116. -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  117. -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  118. box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  119. color: #fff;
  120. font: bold 14px "helvetica neue", helvetica, arial, sans-serif;
  121. line-height: 1;
  122. margin-bottom: 15px;
  123. padding: 8px 0 10px 0;
  124. text-align: center;
  125. text-shadow: 0px -1px 1px #1e2d4d;
  126. text-decoration: none;
  127. width: 225px;
  128. -webkit-background-clip: padding-box; }
  129. a.punch:hover {
  130. -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  131. -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  132. -ms-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  133. -o-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  134. box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
  135. cursor: pointer; }
  136. a.punch:active {
  137. -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  138. -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  139. -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  140. -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  141. box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111;
  142. margin-top: 5px; margin-bottom: 10px }
  143. a img {
  144. border: 0;
  145. }
  146. h1, h2, h3, h4, h5, h6 {
  147. padding-top: 20px;
  148. }
  149. h2 {
  150. font-size: 22px;
  151. }
  152. b.header {
  153. font-size: 18px;
  154. line-height: 35px;
  155. }
  156. span.alias {
  157. font-size: 14px;
  158. font-style: italic;
  159. margin-left: 20px;
  160. }
  161. table {
  162. margin: 15px 0 0; padding: 0;
  163. }
  164. tr, td {
  165. margin: 0; padding: 0;
  166. }
  167. td {
  168. padding: 0px 15px 5px 0;
  169. }
  170. code, pre, tt {
  171. font-family: Monaco, Consolas, "Lucida Console", monospace;
  172. font-size: 12px;
  173. line-height: 18px;
  174. font-style: normal;
  175. }
  176. tt {
  177. padding: 0px 3px;
  178. background: #fff;
  179. border: 1px solid #ddd;
  180. zoom: 1;
  181. }
  182. code {
  183. margin-left: 20px;
  184. }
  185. pre {
  186. font-size: 12px;
  187. padding: 2px 0 2px 15px;
  188. border: 4px solid #bbb; border-top: 0; border-bottom: 0;
  189. margin: 0px 0 25px;
  190. }
  191. img.example_image {
  192. margin: 0px auto;
  193. }
  194. </style>
  195. </head>
  196. <body>
  197. <div id="sidebar" class="interface">
  198. <a class="toc_title" href="#">
  199. Backbone.js <span class="version">(0.9.1)</span>
  200. </a>
  201. <a class="toc_title" href="#introduction">
  202. Introduction
  203. </a>
  204. <a class="toc_title" href="#upgrading">
  205. Upgrading
  206. </a>
  207. <a class="toc_title" href="#Events">
  208. Events
  209. </a>
  210. <ul class="toc_section">
  211. <li>– <a href="#Events-on">on</a></li>
  212. <li>– <a href="#Events-off">off</a></li>
  213. <li>– <a href="#Events-trigger">trigger</a></li>
  214. </ul>
  215. <a class="toc_title" href="#Model">
  216. Model
  217. </a>
  218. <ul class="toc_section">
  219. <li>– <a href="#Model-extend">extend</a></li>
  220. <li>– <a href="#Model-constructor">constructor / initialize</a></li>
  221. <li>– <a href="#Model-get">get</a></li>
  222. <li>– <a href="#Model-set">set</a></li>
  223. <li>– <a href="#Model-escape">escape</a></li>
  224. <li>– <a href="#Model-has">has</a></li>
  225. <li>– <a href="#Model-unset">unset</a></li>
  226. <li>– <a href="#Model-clear">clear</a></li>
  227. <li>– <a href="#Model-id">id</a></li>
  228. <li>– <a href="#Model-idAttribute">idAttribute</a></li>
  229. <li>– <a href="#Model-cid">cid</a></li>
  230. <li>– <a href="#Model-attributes">attributes</a></li>
  231. <li>– <a href="#Model-defaults">defaults</a></li>
  232. <li>- <a href="#Model-toJSON">toJSON</a></li>
  233. <li>– <a href="#Model-fetch">fetch</a></li>
  234. <li>– <a href="#Model-save">save</a></li>
  235. <li>– <a href="#Model-destroy">destroy</a></li>
  236. <li>– <a href="#Model-validate">validate</a></li>
  237. <li>– <a href="#Model-isValid">isValid</a></li>
  238. <li>– <a href="#Model-url">url</a></li>
  239. <li>– <a href="#Model-urlRoot">urlRoot</a></li>
  240. <li>– <a href="#Model-parse">parse</a></li>
  241. <li>– <a href="#Model-clone">clone</a></li>
  242. <li>– <a href="#Model-isNew">isNew</a></li>
  243. <li>– <a href="#Model-change">change</a></li>
  244. <li>– <a href="#Model-hasChanged">hasChanged</a></li>
  245. <li>– <a href="#Model-changedAttributes">changedAttributes</a></li>
  246. <li>– <a href="#Model-previous">previous</a></li>
  247. <li>– <a href="#Model-previousAttributes">previousAttributes</a></li>
  248. </ul>
  249. <a class="toc_title" href="#Collection">
  250. Collection
  251. </a>
  252. <ul class="toc_section">
  253. <li>– <a href="#Collection-extend">extend</a></li>
  254. <li>– <a href="#Collection-model">model</a></li>
  255. <li>– <a href="#Collection-constructor">constructor / initialize</a></li>
  256. <li>– <a href="#Collection-models">models</a></li>
  257. <li>– <a href="#Collection-toJSON">toJSON</a></li>
  258. <li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (28)</b></a></li>
  259. <li>– <a href="#Collection-add">add</a></li>
  260. <li>– <a href="#Collection-remove">remove</a></li>
  261. <li>– <a href="#Collection-get">get</a></li>
  262. <li>– <a href="#Collection-getByCid">getByCid</a></li>
  263. <li>– <a href="#Collection-at">at</a></li>
  264. <li>– <a href="#Collection-length">length</a></li>
  265. <li>– <a href="#Collection-comparator">comparator</a></li>
  266. <li>– <a href="#Collection-sort">sort</a></li>
  267. <li>– <a href="#Collection-pluck">pluck</a></li>
  268. <li>– <a href="#Collection-url">url</a></li>
  269. <li>– <a href="#Collection-parse">parse</a></li>
  270. <li>– <a href="#Collection-fetch">fetch</a></li>
  271. <li>– <a href="#Collection-reset">reset</a></li>
  272. <li>– <a href="#Collection-create">create</a></li>
  273. </ul>
  274. <a class="toc_title" href="#Router">
  275. Router
  276. </a>
  277. <ul class="toc_section">
  278. <li>– <a href="#Router-extend">extend</a></li>
  279. <li>– <a href="#Router-routes">routes</a></li>
  280. <li>– <a href="#Router-constructor">constructor / initialize</a></li>
  281. <li>– <a href="#Router-route">route</a></li>
  282. <li>– <a href="#Router-navigate">navigate</a></li>
  283. </ul>
  284. <a class="toc_title" href="#History">
  285. History
  286. </a>
  287. <ul class="toc_section">
  288. <li>– <a href="#History-start">start</a></li>
  289. </ul>
  290. <a class="toc_title" href="#Sync">
  291. Sync
  292. </a>
  293. <ul class="toc_section">
  294. <li>– <a href="#Sync">Backbone.sync</a></li>
  295. <li>– <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
  296. <li>– <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
  297. </ul>
  298. <a class="toc_title" href="#View">
  299. View
  300. </a>
  301. <ul class="toc_section">
  302. <li>– <a href="#View-extend">extend</a></li>
  303. <li>– <a href="#View-constructor">constructor / initialize</a></li>
  304. <li>– <a href="#View-el">el</a></li>
  305. <li>– <a href="#View-$el">$el</a></li>
  306. <li>– <a href="#View-setElement">setElement</a></li>
  307. <li>– <a href="#View-attributes">attributes</a></li>
  308. <li>– <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
  309. <li>– <a href="#View-render">render</a></li>
  310. <li>– <a href="#View-remove">remove</a></li>
  311. <li>– <a href="#View-make">make</a></li>
  312. <li>– <a href="#View-delegateEvents">delegateEvents</a></li>
  313. <li>– <a href="#View-undelegateEvents">undelegateEvents</a></li>
  314. </ul>
  315. <a class="toc_title" href="#Utility">
  316. Utility
  317. </a>
  318. <ul class="toc_section">
  319. <li>– <a href="#Utility-noConflict">noConflict</a></li>
  320. <li>– <a href="#Utility-setDomLibrary">setDomLibrary</a></li>
  321. </ul>
  322. <a class="toc_title" href="#examples">
  323. Examples
  324. </a>
  325. <ul class="toc_section">
  326. <li>– <a href="#examples-todos">Todos</a></li>
  327. <li>– <a href="#examples-documentcloud">DocumentCloud</a></li>
  328. <li>– <a href="#examples-linkedin">LinkedIn Mobile</a></li>
  329. <li>– <a href="#examples-flow">Flow</a></li>
  330. <li>– <a href="#examples-audiovroom">AudioVroom</a></li>
  331. <li>– <a href="#examples-foursquare">Foursquare</a></li>
  332. <li>– <a href="#examples-do">Do</a></li>
  333. <li>– <a href="#examples-posterous">Posterous Spaces</a></li>
  334. <li>– <a href="#examples-groupon">Groupon Now!</a></li>
  335. <li>– <a href="#examples-basecamp">Basecamp Mobile</a></li>
  336. <li>– <a href="#examples-slavery-footprint">Slavery Footprint</a></li>
  337. <li>- <a href="#examples-stripe">Stripe</a></li>
  338. <li>– <a href="#examples-diaspora">Diaspora</a></li>
  339. <li>– <a href="#examples-trajectory">Trajectory</a></li>
  340. <li>– <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
  341. <li>– <a href="#examples-pandora">Pandora</a></li>
  342. <li>- <a href="#examples-code-school">Code School</a></li>
  343. <li>– <a href="#examples-cloudapp">CloudApp</a></li>
  344. <li>– <a href="#examples-seatgeek">SeatGeek</a></li>
  345. <li>– <a href="#examples-grove">Grove.io</a></li>
  346. <li>– <a href="#examples-kicksend">Kicksend</a></li>
  347. <li>– <a href="#examples-shortmail">Shortmail</a></li>
  348. <li>– <a href="#examples-battlefield">Battlefield Play4Free</a></li>
  349. <li>– <a href="#examples-salon">Salon.io</a></li>
  350. <li>– <a href="#examples-quoteroller">Quote Roller</a></li>
  351. <li>– <a href="#examples-tilemill">TileMill</a></li>
  352. <li>- <a href="#examples-blossom">Blossom</a></li>
  353. <li>- <a href="#examples-animoto">Animoto</a></li>
  354. <li>- <a href="#examples-decide">Decide</a></li>
  355. <li>- <a href="#examples-trello">Trello</a></li>
  356. <li>- <a href="#examples-bittorrent">BitTorrent</a></li>
  357. <li>- <a href="#examples-ducksboard">Ducksboard</a></li>
  358. <li>- <a href="#examples-quietwrite">QuietWrite</a></li>
  359. <li>- <a href="#examples-tzigla">Tzigla</a></li>
  360. </ul>
  361. <a class="toc_title" href="#faq">
  362. F.A.Q.
  363. </a>
  364. <ul class="toc_section">
  365. <li>– <a href="#FAQ-events">Catalog of Events</a></li>
  366. <li>– <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
  367. <li>– <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
  368. <li>– <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
  369. <li>– <a href="#FAQ-extending">Extending Backbone</a></li>
  370. <li>– <a href="#FAQ-mvc">Traditional MVC</a></li>
  371. <li>– <a href="#FAQ-this">Binding "this"</a></li>
  372. <li>– <a href="#FAQ-rails">Working with Rails</a></li>
  373. </ul>
  374. <a class="toc_title" href="#changelog">
  375. Change Log
  376. </a>
  377. </div>
  378. <div class="container">
  379. <p>
  380. <img style="width: 451px; height: 80px;" src="docs/images/backbone.png" alt="Backbone.js" />
  381. </p>
  382. <p>
  383. Backbone.js gives structure to your serious JavaScript web applications
  384. by supplying <b>models</b> with key-value binding and custom events,
  385. <b>collections</b> with a rich API of enumerable functions,
  386. <b>views</b> with declarative event handling, and connects it all to your
  387. existing API over a RESTful JSON interface.
  388. </p>
  389. <p>
  390. The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
  391. and the <a href="docs/backbone.html">annotated source code</a> is available,
  392. as well as an online <a href="test/test.html">test suite</a>,
  393. an <a href="examples/todos/index.html">example application</a>,
  394. a <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>
  395. and a <a href="#examples">long list of real-world projects</a> that use Backbone.
  396. </p>
  397. <p>
  398. You can report bugs and discuss features on the
  399. <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
  400. on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
  401. <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
  402. add pages to the a <a href="https://github.com/documentcloud/backbone/wiki">wiki</a>
  403. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  404. </p>
  405. <p>
  406. <i>
  407. Backbone is an open-source component of
  408. <a href="http://documentcloud.org/">DocumentCloud</a>.
  409. </i>
  410. </p>
  411. <h2 id="downloads">
  412. Downloads &amp; Dependencies
  413. <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
  414. </h2>
  415. <table>
  416. <tr>
  417. <td><a class="punch" href="backbone.js">Development Version (0.9.1)</a></td>
  418. <td><i>47kb, Full source, lots of comments</i></td>
  419. </tr>
  420. <tr>
  421. <td><a class="punch" href="backbone-min.js">Production Version (0.9.1)</a></td>
  422. <td><i>5.3kb, Packed and gzipped</i></td>
  423. </tr>
  424. </table>
  425. <p>
  426. Backbone's only hard dependency is
  427. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> <small>( > 1.3.1)</small>.
  428. For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
  429. and DOM manipulation with <a href="#View">Backbone.View</a>, include
  430. <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
  431. <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or
  432. <a href="http://zeptojs.com/">Zepto</a>.
  433. </p>
  434. <h2 id="introduction">Introduction</h2>
  435. <p>
  436. When working on a web application that involves a lot of JavaScript, one
  437. of the first things you learn is to stop tying your data to the DOM. It's all
  438. too easy to create JavaScript applications that end up as tangled piles of
  439. jQuery selectors and callbacks, all trying frantically to keep data in
  440. sync between the HTML UI, your JavaScript logic, and the database on your
  441. server. For rich client-side applications, a more structured approach
  442. is often helpful.
  443. </p>
  444. <p>
  445. With Backbone, you represent your data as
  446. <a href="#Model">Models</a>, which can be created, validated, destroyed,
  447. and saved to the server. Whenever a UI action causes an attribute of
  448. a model to change, the model triggers a <i>"change"</i> event; all
  449. the <a href="#View">Views</a> that display the model's state can be notified of the
  450. change, so that they are able to respond accordingly, re-rendering themselves with
  451. the new information. In a finished Backbone app, you don't have to write the glue
  452. code that looks into the DOM to find an element with a specific <i>id</i>,
  453. and update the HTML manually
  454. &mdash; when the model changes, the views simply update themselves.
  455. </p>
  456. <p>
  457. Many of the examples that follow are runnable. Click the <i>play</i> button
  458. to execute them.
  459. </p>
  460. <h2 id="upgrading">Upgrading to 0.9</h2>
  461. <p>
  462. Backbone's <b>0.9</b> series should be considered as a release candidate
  463. for an upcoming <b>1.0</b>. Some APIs have changed, and while there is a
  464. <a href="#changelog">change log</a> available, and many new features to
  465. take advantage of, there are a few specific changes where you'll need
  466. to take care:
  467. </p>
  468. <ul>
  469. <li>
  470. If you've ever manually set <tt>this.el</tt> in a Backbone View to be a
  471. particular DOM element, you'll want to use
  472. <a href="#View-setElement">setElement</a> instead.
  473. </li>
  474. <li>
  475. Creating and destroying models is now optimistic. Pass <tt>{wait: true}</tt>
  476. if you need the previous behavior of waiting for the server to acknowledge
  477. success. You can now also pass <tt>{wait: true}</tt> to <a href="#Model-save">save</a> calls.
  478. </li>
  479. <li>
  480. If you have been writing a fair amount of <tt>$(view.el)</tt>, there's now
  481. a cached reference for that jQuery object: <a href="#View-$el">$el</a>.
  482. </li>
  483. <li>
  484. If you're upgrading, make sure you also upgrade your version of Underscore.js
  485. to the latest &mdash; 1.3.1 or greater.
  486. </li>
  487. </ul>
  488. <h2 id="Events">Backbone.Events</h2>
  489. <p>
  490. <b>Events</b> is a module that can be mixed in to any object, giving the
  491. object the ability to bind and trigger custom named events. Events do not
  492. have to be declared before they are bound, and may take passed arguments.
  493. For example:
  494. </p>
  495. <pre class="runnable">
  496. var object = {};
  497. _.extend(object, Backbone.Events);
  498. object.on("alert", function(msg) {
  499. alert("Triggered " + msg);
  500. });
  501. object.trigger("alert", "an event");
  502. </pre>
  503. <p>
  504. For example, to make a handy event dispatcher that can coordinate events
  505. among different areas of your application: <tt>var dispatcher = _.clone(Backbone.Events)</tt>
  506. </p>
  507. <p id="Events-on">
  508. <b class="header">on</b><code>object.on(event, callback, [context])</code><span class="alias">Alias: bind</span>
  509. <br />
  510. Bind a <b>callback</b> function to an object. The callback will be invoked
  511. whenever the <b>event</b> is fired.
  512. If you have a large number of different events on a page, the convention is to use colons to
  513. namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>.
  514. The event string may also be a space-delimited list of several events...
  515. </p>
  516. <pre>
  517. book.on("change:title change:author", ...);
  518. </pre>
  519. <p>
  520. To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
  521. pass the optional third argument: <tt>model.on('change', this.render, this)</tt>
  522. </p>
  523. <p>
  524. Callbacks bound to the special
  525. <tt>"all"</tt> event will be triggered when any event occurs, and are passed
  526. the name of the event as the first argument. For example, to proxy all events
  527. from one object to another:
  528. </p>
  529. <pre>
  530. proxy.on("all", function(eventName) {
  531. object.trigger(eventName);
  532. });
  533. </pre>
  534. <p id="Events-off">
  535. <b class="header">off</b><code>object.off([event], [callback], [context])</code><span class="alias">Alias: unbind</span>
  536. <br />
  537. Remove a previously-bound <b>callback</b> function from an object. If no
  538. <b>context</b> is specified, all of the versions of the callback with
  539. different contexts will be removed. If no
  540. callback is specified, all callbacks for the <b>event</b> will be
  541. removed. If no event is specified, <i>all</i> event callbacks on the object
  542. will be removed.
  543. </p>
  544. <pre>
  545. object.off("change", onChange); // Removes just the onChange callback.
  546. object.off("change"); // Removes all "change" callbacks.
  547. object.off(); // Removes all callbacks on object.
  548. </pre>
  549. <p id="Events-trigger">
  550. <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
  551. <br />
  552. Trigger callbacks for the given <b>event</b>, or space-delimited list of events.
  553. Subsequent arguments to <b>trigger</b> will be passed along to the
  554. event callbacks.
  555. </p>
  556. <h2 id="Model">Backbone.Model</h2>
  557. <p>
  558. <b>Models</b> are the heart of any JavaScript application, containing
  559. the interactive data as well as a large part of the logic surrounding it:
  560. conversions, validations, computed properties, and access control. You
  561. extend <b>Backbone.Model</b> with your domain-specific methods, and
  562. <b>Model</b> provides a basic set of functionality for managing changes.
  563. </p>
  564. <p>
  565. The following is a contrived example, but it demonstrates defining a model
  566. with a custom method, setting an attribute, and firing an event keyed
  567. to changes in that specific attribute.
  568. After running this code once, <tt>sidebar</tt> will be
  569. available in your browser's console, so you can play around with it.
  570. </p>
  571. <pre class="runnable">
  572. var Sidebar = Backbone.Model.extend({
  573. promptColor: function() {
  574. var cssColor = prompt("Please enter a CSS color:");
  575. this.set({color: cssColor});
  576. }
  577. });
  578. window.sidebar = new Sidebar;
  579. sidebar.on('change:color', function(model, color) {
  580. $('#sidebar').css({background: color});
  581. });
  582. sidebar.set({color: 'white'});
  583. sidebar.promptColor();
  584. </pre>
  585. <p id="Model-extend">
  586. <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
  587. <br />
  588. To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
  589. and provide instance <b>properties</b>, as well as optional
  590. <b>classProperties</b> to be attached directly to the constructor function.
  591. </p>
  592. <p>
  593. <b>extend</b> correctly sets up the prototype chain, so subclasses created
  594. with <b>extend</b> can be further extended and subclassed as far as you like.
  595. </p>
  596. <pre>
  597. var Note = Backbone.Model.extend({
  598. initialize: function() { ... },
  599. author: function() { ... },
  600. coordinates: function() { ... },
  601. allowedToEdit: function(account) {
  602. return true;
  603. }
  604. });
  605. var PrivateNote = Note.extend({
  606. allowedToEdit: function(account) {
  607. return account.owns(this);
  608. }
  609. });
  610. </pre>
  611. <p class="warning">
  612. Brief aside on <tt>super</tt>: JavaScript does not provide
  613. a simple way to call super &mdash; the function of the same name defined
  614. higher on the prototype chain. If you override a core function like
  615. <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
  616. parent object's implementation, you'll have to explicitly call it, along these lines:
  617. </p>
  618. <pre>
  619. var Note = Backbone.Model.extend({
  620. set: function(attributes, options) {
  621. Backbone.Model.prototype.set.call(this, attributes, options);
  622. ...
  623. }
  624. });
  625. </pre>
  626. <p id="Model-constructor">
  627. <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
  628. <br />
  629. When creating an instance of a model, you can pass in the initial values
  630. of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
  631. model. If you define an <b>initialize</b> function, it will be invoked when
  632. the model is created.
  633. </p>
  634. <pre>
  635. new Book({
  636. title: "One Thousand and One Nights",
  637. author: "Scheherazade"
  638. });
  639. </pre>
  640. <p>
  641. In rare cases, if you're looking to get fancy,
  642. you may want to override <b>constructor</b>, which allows
  643. you to replace the actual constructor function for your model.
  644. </p>
  645. <p id="Model-get">
  646. <b class="header">get</b><code>model.get(attribute)</code>
  647. <br />
  648. Get the current value of an attribute from the model. For example:
  649. <tt>note.get("title")</tt>
  650. </p>
  651. <p id="Model-set">
  652. <b class="header">set</b><code>model.set(attributes, [options])</code>
  653. <br />
  654. Set a hash of attributes (one or many) on the model. If any of the attributes
  655. change the models state, a <tt>"change"</tt> event will be triggered, unless
  656. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  657. attributes are also triggered, and you can bind to those as well, for example:
  658. <tt>change:title</tt>, and <tt>change:content</tt>. You may also pass
  659. individual keys and values.
  660. </p>
  661. <pre>
  662. note.set({title: "March 20", content: "In his eyes she eclipses..."});
  663. book.set("title", "A Scandal in Bohemia");
  664. </pre>
  665. <p>
  666. If the model has a <a href="#Model-validate">validate</a> method,
  667. it will be validated before the attributes are set, no changes will
  668. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  669. Otherwise, <b>set</b> returns a reference to the model.
  670. You may also pass an <tt>error</tt>
  671. callback in the options, which will be invoked instead of triggering an
  672. <tt>"error"</tt> event, should validation fail.
  673. </p>
  674. <p id="Model-escape">
  675. <b class="header">escape</b><code>model.escape(attribute)</code>
  676. <br />
  677. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  678. of a model's attribute. If you're interpolating data from the model into
  679. HTML, using <b>escape</b> to retrieve attributes will prevent
  680. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  681. </p>
  682. <pre class="runnable">
  683. var hacker = new Backbone.Model({
  684. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  685. });
  686. alert(hacker.escape('name'));
  687. </pre>
  688. <p id="Model-has">
  689. <b class="header">has</b><code>model.has(attribute)</code>
  690. <br />
  691. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  692. value.
  693. </p>
  694. <pre>
  695. if (note.has("title")) {
  696. ...
  697. }
  698. </pre>
  699. <p id="Model-unset">
  700. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  701. <br />
  702. Remove an attribute by deleting it from the internal attributes hash.
  703. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  704. </p>
  705. <p id="Model-clear">
  706. <b class="header">clear</b><code>model.clear([options])</code>
  707. <br />
  708. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  709. <tt>silent</tt> is passed as an option.
  710. </p>
  711. <p id="Model-id">
  712. <b class="header">id</b><code>model.id</code>
  713. <br />
  714. A special property of models, the <b>id</b> is an arbitrary string
  715. (integer id or UUID). If you set the <b>id</b> in the
  716. attributes hash, it will be copied onto the model as a direct property.
  717. Models can be retrieved by id from collections, and the id is used to generate
  718. model URLs by default.
  719. </p>
  720. <p id="Model-idAttribute">
  721. <b class="header">idAttribute</b><code>model.idAttribute</code>
  722. <br />
  723. A model's unique identifier is stored under the <tt>id</tt> attribute.
  724. If you're directly communicating with a backend (CouchDB, MongoDB) that uses
  725. a different unique key, you may set a Model's <tt>idAttribute</tt> to
  726. transparently map from that key to <tt>id</tt>.
  727. <pre class="runnable">
  728. var Meal = Backbone.Model.extend({
  729. idAttribute: "_id"
  730. });
  731. var cake = new Meal({ _id: 1, name: "Cake" });
  732. alert("Cake id: " + cake.id);
  733. </pre>
  734. </p>
  735. <p id="Model-cid">
  736. <b class="header">cid</b><code>model.cid</code>
  737. <br />
  738. A special property of models, the <b>cid</b> or client id is a unique identifier
  739. automatically assigned to all models when they're first created. Client ids
  740. are handy when the model has not yet been saved to the server, and does not
  741. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  742. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  743. </p>
  744. <p id="Model-attributes">
  745. <b class="header">attributes</b><code>model.attributes</code>
  746. <br />
  747. The <b>attributes</b> property is the internal hash containing the model's
  748. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  749. them directly. If you'd like to retrieve and munge a copy of the model's
  750. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  751. </p>
  752. <p id="Model-defaults">
  753. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  754. <br />
  755. The <b>defaults</b> hash (or function) can be used to specify the default
  756. attributes for your model. When creating an instance of the model,
  757. any unspecified attributes will be set to their default value.
  758. </p>
  759. <pre class="runnable">
  760. var Meal = Backbone.Model.extend({
  761. defaults: {
  762. "appetizer": "caesar salad",
  763. "entree": "ravioli",
  764. "dessert": "cheesecake"
  765. }
  766. });
  767. alert("Dessert will be " + (new Meal).get('dessert'));
  768. </pre>
  769. <p class="warning">
  770. Remember that in JavaScript, objects are passed by reference, so if you
  771. include an object as a default value, it will be shared among all instances.
  772. </p>
  773. <p id="Model-toJSON">
  774. <b class="header">toJSON</b><code>model.toJSON()</code>
  775. <br />
  776. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  777. This can be used for persistence, serialization, or for augmentation before
  778. being handed off to a view. The name of this method is a bit confusing, as
  779. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  780. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  781. </p>
  782. <pre class="runnable">
  783. var artist = new Backbone.Model({
  784. firstName: "Wassily",
  785. lastName: "Kandinsky"
  786. });
  787. artist.set({birthday: "December 16, 1866"});
  788. alert(JSON.stringify(artist));
  789. </pre>
  790. <p id="Model-fetch">
  791. <b class="header">fetch</b><code>model.fetch([options])</code>
  792. <br />
  793. Resets the model's state from the server. Useful if the model has never
  794. been populated with data, or if you'd like to ensure that you have the
  795. latest server state. A <tt>"change"</tt> event will be triggered if the
  796. server's state differs from the current attributes. Accepts
  797. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  798. are passed <tt>(model, response)</tt> as arguments.
  799. </p>
  800. <pre>
  801. // Poll every 10 seconds to keep the channel model up-to-date.
  802. setInterval(function() {
  803. channel.fetch();
  804. }, 10000);
  805. </pre>
  806. <p id="Model-save">
  807. <b class="header">save</b><code>model.save([attributes], [options])</code>
  808. <br />
  809. Save a model to your database (or alternative persistence layer),
  810. by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
  811. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  812. you'd like to change &mdash; keys that aren't mentioned won't be altered &mdash; but,
  813. a <i>complete representation</i> of the resource will be sent to the server.
  814. As with <tt>set</tt>, you may pass individual keys and values instead of a hash.
  815. If the model has a <a href="#Model-validate">validate</a>
  816. method, and validation fails, the model will not be saved. If the model
  817. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  818. (HTTP <tt>POST</tt>), if the model already
  819. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  820. </p>
  821. <p>
  822. Calling <tt>save</tt> with new attributes will cause a <tt>"change"</tt>
  823. event immediately, and a <tt>"sync"</tt> event after the server has acknowledged
  824. the successful change. Pass <tt>{wait: true}</tt> if you'd like to wait
  825. for the server before setting the new attributes on the model.
  826. </p>
  827. <p>
  828. In the following example, notice how our overridden version
  829. of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
  830. the first time the model is saved and an <tt>"update"</tt>
  831. request the second time.
  832. </p>
  833. <pre class="runnable">
  834. Backbone.sync = function(method, model) {
  835. alert(method + ": " + JSON.stringify(model));
  836. model.id = 1;
  837. };
  838. var book = new Backbone.Model({
  839. title: "The Rough Riders",
  840. author: "Theodore Roosevelt"
  841. });
  842. book.save();
  843. book.save({author: "Teddy"});
  844. </pre>
  845. <p>
  846. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  847. options hash, which are passed <tt>(model, response)</tt> as arguments.
  848. The <tt>error</tt> callback will also be invoked if the model has a
  849. <tt>validate</tt> method, and validation fails. If a server-side
  850. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  851. an error response in text or JSON.
  852. </p>
  853. <pre>
  854. book.save("author", "F.D.R.", {error: function(){ ... }});
  855. </pre>
  856. <p id="Model-destroy">
  857. <b class="header">destroy</b><code>model.destroy([options])</code>
  858. <br />
  859. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  860. request to <a href="#Sync">Backbone.sync</a>. Accepts
  861. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  862. Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
  863. through any collections that contain it, and a <tt>"sync"</tt> event, after
  864. the server has successfully acknowledged the model's deletion. Pass
  865. <tt>{wait: true}</tt> if you'd like to wait for the server to respond
  866. before removing the model from the collection.
  867. </p>
  868. <pre>
  869. book.destroy({success: function(model, response) {
  870. ...
  871. }});
  872. </pre>
  873. <p id="Model-validate">
  874. <b class="header">validate</b><code>model.validate(attributes)</code>
  875. <br />
  876. This method is left undefined, and you're encouraged to override it with
  877. your custom validation logic, if you have any that can be performed
  878. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  879. <tt>save</tt>, and is passed the attributes that are about to be updated.
  880. If the model and attributes are valid, don't return anything from <b>validate</b>;
  881. if the attributes are invalid, return an error of your choosing. It
  882. can be as simple as a string error message to be displayed, or a complete
  883. error object that describes the error programmatically. <tt>set</tt> and
  884. <tt>save</tt> will not continue if <b>validate</b> returns an error.
  885. Failed validations trigger an <tt>"error"</tt> event.
  886. </p>
  887. <pre class="runnable">
  888. var Chapter = Backbone.Model.extend({
  889. validate: function(attrs) {
  890. if (attrs.end < attrs.start) {
  891. return "can't end before it starts";
  892. }
  893. }
  894. });
  895. var one = new Chapter({
  896. title : "Chapter One: The Beginning"
  897. });
  898. one.on("error", function(model, error) {
  899. alert(model.get("title") + " " + error);
  900. });
  901. one.set({
  902. start: 15,
  903. end: 10
  904. });
  905. </pre>
  906. <p>
  907. <tt>"error"</tt> events are useful for providing coarse-grained error
  908. messages at the model or collection level, but if you have a specific view
  909. that can better handle the error, you may override and suppress the event
  910. by passing an <tt>error</tt> callback directly:
  911. </p>
  912. <pre>
  913. account.set({access: "unlimited"}, {
  914. error: function(model, error) {
  915. alert(error);
  916. }
  917. });
  918. </pre>
  919. <p id="Model-isValid">
  920. <b class="header">isValid</b><code>model.isValid()</code>
  921. <br />
  922. Models may enter an invalid state if you make changes to them silently
  923. ... useful when dealing with form input. Call <tt>model.isValid()</tt>
  924. to check if the model is currently in a valid state, according to your
  925. <tt>validate</tt> function.
  926. </p>
  927. <p id="Model-url">
  928. <b class="header">url</b><code>model.url()</code>
  929. <br />
  930. Returns the relative URL where the model's resource would be located on
  931. the server. If your models are located somewhere else, override this method
  932. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  933. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  934. </p>
  935. <p>
  936. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  937. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  938. property, if all models of this class share a common root URL.
  939. A model with an id of <tt>101</tt>, stored in a
  940. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  941. would have this URL: <tt>"/documents/7/notes/101"</tt>
  942. </p>
  943. <p id="Model-urlRoot">
  944. <b class="header">urlRoot</b><code>model.urlRoot</code>
  945. <br />
  946. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  947. to enable the default <a href="#Model-url">url</a> function to generate
  948. URLs based on the model id. <tt>"/[urlRoot]/id"</tt><br />
  949. Note that <tt>urlRoot</tt> may also be defined as a function.
  950. </p>
  951. <pre class="runnable">
  952. var Book = Backbone.Model.extend({urlRoot : '/books'});
  953. var solaris = new Book({id: "1083-lem-solaris"});
  954. alert(solaris.url());
  955. </pre>
  956. <p id="Model-parse">
  957. <b class="header">parse</b><code>model.parse(response)</code>
  958. <br />
  959. <b>parse</b> is called whenever a model's data is returned by the
  960. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  961. The function is passed the raw <tt>response</tt> object, and should return
  962. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  963. default implementation is a no-op, simply passing through the JSON response.
  964. Override this if you need to work with a preexisting API, or better namespace
  965. your responses.
  966. </p>
  967. <p>
  968. If you're working with a Rails backend, you'll notice that Rails' default
  969. <tt>to_json</tt> implementation includes a model's attributes under a
  970. namespace. To disable this behavior for seamless Backbone integration, set:
  971. </p>
  972. <pre>
  973. ActiveRecord::Base.include_root_in_json = false
  974. </pre>
  975. <p id="Model-clone">
  976. <b class="header">clone</b><code>model.clone()</code>
  977. <br />
  978. Returns a new instance of the model with identical attributes.
  979. </p>
  980. <p id="Model-isNew">
  981. <b class="header">isNew</b><code>model.isNew()</code>
  982. <br />
  983. Has this model been saved to the server yet? If the model does not yet have
  984. an <tt>id</tt>, it is considered to be new.
  985. </p>
  986. <p id="Model-change">
  987. <b class="header">change</b><code>model.change()</code>
  988. <br />
  989. Manually trigger the <tt>"change"</tt> event and a <tt>"change:attribute"</tt>
  990. event for each attribute that has changed. If you've been passing
  991. <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  992. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  993. when you're all finished.
  994. </p>
  995. <p id="Model-hasChanged">
  996. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  997. <br />
  998. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  999. is passed, returns <tt>true</tt> if that specific attribute has changed.
  1000. </p>
  1001. <p class="warning">
  1002. Note that this method, and the following change-related ones,
  1003. are only useful during the course of a <tt>"change"</tt> event.
  1004. </p>
  1005. <pre>
  1006. book.on("change", function() {
  1007. if (book.hasChanged("title")) {
  1008. ...
  1009. }
  1010. });
  1011. </pre>
  1012. <p id="Model-changedAttributes">
  1013. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  1014. <br />
  1015. Retrieve a hash of only the model's attributes that have changed. Optionally,
  1016. an external <b>attributes</b> hash can be passed in, returning
  1017. the attributes in that hash which differ from the model. This can be used
  1018. to figure out which portions of a view should be updated, or what calls
  1019. need to be made to sync the changes to the server.
  1020. </p>
  1021. <p id="Model-previous">
  1022. <b class="header">previous</b><code>model.previous(attribute)</code>
  1023. <br />
  1024. During a <tt>"change"</tt> event, this method can be used to get the
  1025. previous value of a changed attribute.
  1026. </p>
  1027. <pre class="runnable">
  1028. var bill = new Backbone.Model({
  1029. name: "Bill Smith"
  1030. });
  1031. bill.on("change:name", function(model, name) {
  1032. alert("Changed name from " + bill.previous("name") + " to " + name);
  1033. });
  1034. bill.set({name : "Bill Jones"});
  1035. </pre>
  1036. <p id="Model-previousAttributes">
  1037. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  1038. <br />
  1039. Return a copy of the model's previous attributes. Useful for getting a
  1040. diff between versions of a model, or getting back to a valid state after
  1041. an error occurs.
  1042. </p>
  1043. <h2 id="Collection">Backbone.Collection</h2>
  1044. <p>
  1045. Collections are ordered sets of models. You can bind <tt>"change"</tt> events
  1046. to be notified when any model in the collection has been modified,
  1047. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  1048. the collection from the server, and use a full suite of
  1049. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  1050. </p>
  1051. <p>
  1052. Any event that is triggered on a model in a collection will also be
  1053. triggered on the collection directly, for convenience.
  1054. This allows you to listen for changes to specific attributes in any
  1055. model in a collection, for example:
  1056. <tt>Documents.on("change:selected", ...)</tt>
  1057. </p>
  1058. <p id="Collection-extend">
  1059. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  1060. <br />
  1061. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  1062. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  1063. directly to the collection's constructor function.
  1064. </p>
  1065. <p id="Collection-model">
  1066. <b class="header">model</b><code>collection.model</code>
  1067. <br />
  1068. Override this property to specify the model class that the collection
  1069. contains. If defined, you can pass raw attributes objects (and arrays) to
  1070. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  1071. and <a href="#Collection-reset">reset</a>, and the attributes will be
  1072. converted into a model of the proper type.
  1073. </p>
  1074. <pre>
  1075. var Library = Backbone.Collection.extend({
  1076. model: Book
  1077. });
  1078. </pre>
  1079. <p id="Collection-constructor">
  1080. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  1081. <br />
  1082. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  1083. The collection's <a href="#Collection-comparator">comparator</a> function
  1084. may be included as an option. If you define an <b>initialize</b> function, it will be
  1085. invoked when the collection is created.
  1086. </p>
  1087. <pre>
  1088. var tabs = new TabSet([tab1, tab2, tab3]);
  1089. </pre>
  1090. <p id="Collection-models">
  1091. <b class="header">models</b><code>collection.models</code>
  1092. <br />
  1093. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  1094. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  1095. to access model objects, but occasionally a direct reference to the array
  1096. is desired.
  1097. </p>
  1098. <p id="Collection-toJSON">
  1099. <b class="header">toJSON</b><code>collection.toJSON()</code>
  1100. <br />
  1101. Return an array containing the attributes hash of each model in the
  1102. collection. This can be used to serialize and persist the
  1103. collection as a whole. The name of this method is a bit confusing, because
  1104. it conforms to
  1105. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  1106. </p>
  1107. <pre class="runnable">
  1108. var collection = new Backbone.Collection([
  1109. {name: "Tim", age: 5},
  1110. {name: "Ida", age: 26},
  1111. {name: "Rob", age: 55}
  1112. ]);
  1113. alert(JSON.stringify(collection));
  1114. </pre>
  1115. <p id="Collection-Underscore-Methods">
  1116. <b class="header">Underscore Methods (28)</b>
  1117. <br />
  1118. Backbone proxies to <b>Underscore.js</b> to provide 28 iteration functions
  1119. on <b>Backbone.Collection</b>. They aren't all documented here, but
  1120. you can take a look at the Underscore documentation for the full details&hellip;
  1121. </p>
  1122. <ul class="small">
  1123. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  1124. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  1125. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  1126. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  1127. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  1128. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  1129. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  1130. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  1131. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  1132. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  1133. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  1134. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  1135. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  1136. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  1137. <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li>
  1138. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  1139. <li><a href="http://documentcloud.github.com/underscore/#shuffle">shuffle</a></li>
  1140. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  1141. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  1142. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  1143. <li><a href="http://documentcloud.github.com/underscore/#initial">initial</a></li>
  1144. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  1145. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  1146. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  1147. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  1148. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  1149. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  1150. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  1151. </ul>
  1152. <pre>
  1153. Books.each(function(book) {
  1154. book.publish();
  1155. });
  1156. var titles = Books.map(function(book) {
  1157. return book.get("title");
  1158. });
  1159. var publishedBooks = Books.filter(function(book) {
  1160. return book.get("published") === true;
  1161. });
  1162. var alphabetical = Books.sortBy(function(book) {
  1163. return book.author.get("name").toLowerCase();
  1164. });
  1165. </pre>
  1166. <p id="Collection-add">
  1167. <b class="header">add</b><code>collection.add(models, [options])</code>
  1168. <br />
  1169. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  1170. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  1171. <a href="#Collection-model">model</a> property is defined, you may also pass
  1172. raw attributes objects, and have them be vivified as instances of the model.
  1173. Pass <tt>{at: index}</tt> to splice the model into the collection at the
  1174. specified <tt>index</tt>. Likewise, if you're a callback listening to a
  1175. collection's <tt>"add"</tt> event, <tt>options.index</tt> will tell you the
  1176. index at which the model is being added to the collection.
  1177. </p>
  1178. <pre class="runnable">
  1179. var ships = new Backbone.Collection;
  1180. ships.on("add", function(ship) {
  1181. alert("Ahoy " + ship.get("name") + "!");
  1182. });
  1183. ships.add([
  1184. {name: "Flying Dutchman"},
  1185. {name: "Black Pearl"}
  1186. ]);
  1187. </pre>
  1188. <p id="Collection-remove">
  1189. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  1190. <br />
  1191. Remove a model (or an array of models) from the collection. Fires a
  1192. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  1193. to suppress. If you're a callback listening to the <tt>"remove"</tt> event,
  1194. the index at which the model is being removed from the collection is available
  1195. as <tt>options.index</tt>.
  1196. </p>
  1197. <p id="Collection-get">
  1198. <b class="header">get</b><code>collection.get(id)</code>
  1199. <br />
  1200. Get a model from a collection, specified by <b>id</b>.
  1201. </p>
  1202. <pre>
  1203. var book = Library.get(110);
  1204. </pre>
  1205. <p id="Collection-getByCid">
  1206. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  1207. <br />
  1208. Get a model from a collection, specified by client id. The client id
  1209. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  1210. a model is created. Useful for models which have not yet been saved to
  1211. the server, and do not yet have true ids.
  1212. </p>
  1213. <p id="Collection-at">
  1214. <b class="header">at</b><code>collection.at(index)</code>
  1215. <br />
  1216. Get a model from a collection, specified by index. Useful if your collection
  1217. is sorted, and if your collection isn't sorted, <b>at</b> will still
  1218. retrieve models in insertion order.
  1219. </p>
  1220. <p id="Collection-length">
  1221. <b class="header">length</b><code>collection.length</code>
  1222. <br />
  1223. Like an array, a Collection maintains a <tt>length</tt> property, counting
  1224. the number of models it contains.
  1225. </p>
  1226. <p id="Collection-comparator">
  1227. <b class="header">comparator</b><code>collection.comparator</code>
  1228. <br />
  1229. By default there is no <b>comparator</b> function on a collection.
  1230. If you define a comparator, it will be used to maintain
  1231. the collection in sorted order. This means that as models are added,
  1232. they are inserted at the correct index in <tt>collection.models</tt>.
  1233. Comparator function can be defined as either a
  1234. <a href="http://underscorejs.org/#sortBy">sortBy</a>
  1235. (pass a function that takes a single argument),
  1236. or as a
  1237. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort">sort</a>
  1238. (pass a comparator function that expects two arguments).
  1239. </p>
  1240. <p>
  1241. "sort" comparator functions take a model and return a numeric or string
  1242. value by which the model should be ordered relative to others.
  1243. "sortBy" comparator functions take two models, and return <tt>-1</tt> if
  1244. the first model should come before the second, <tt>0</tt> if they are of
  1245. the same rank and <tt>1</tt> if the first model should come after.
  1246. </p>
  1247. <p>
  1248. Note how even though all of the chapters in this example are added backwards,
  1249. they come out in the proper order:
  1250. </p>
  1251. <pre class="runnable">
  1252. var Chapter = Backbone.Model;
  1253. var chapters = new Backbone.Collection;
  1254. chapters.comparator = function(chapter) {
  1255. return chapter.get("page");
  1256. };
  1257. chapters.add(new Chapter({page: 9, title: "The End"}));
  1258. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1259. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1260. alert(chapters.pluck('title'));
  1261. </pre>
  1262. <p class="warning">
  1263. Collections with comparator functions will not automatically re-sort if you
  1264. later change model attributes, so you may wish to call <tt>sort</tt> after
  1265. changing model attributes that would affect the order.
  1266. </p>
  1267. <p id="Collection-sort">
  1268. <b class="header">sort</b><code>collection.sort([options])</code>
  1269. <br />
  1270. Force a collection to re-sort itself. You don't need to call this under
  1271. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1272. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1273. triggers the collection's <tt>"reset"</tt> event, unless silenced by passing
  1274. <tt>{silent: true}</tt>
  1275. </p>
  1276. <p id="Collection-pluck">
  1277. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1278. <br />
  1279. Pluck an attribute from each model in the collection. Equivalent to calling
  1280. <tt>map</tt>, and returning a single attribute from the iterator.
  1281. </p>
  1282. <pre class="runnable">
  1283. var stooges = new Backbone.Collection([
  1284. new Backbone.Model({name: "Curly"}),
  1285. new Backbone.Model({name: "Larry"}),
  1286. new Backbone.Model({name: "Moe"})
  1287. ]);
  1288. var names = stooges.pluck("name");
  1289. alert(JSON.stringify(names));
  1290. </pre>
  1291. <p id="Collection-url">
  1292. <b class="header">url</b><code>collection.url or collection.url()</code>
  1293. <br />
  1294. Set the <b>url</b> property (or function) on a collection to reference
  1295. its location on the server. Models within the collection will use <b>url</b>
  1296. to construct URLs of their own.
  1297. </p>
  1298. <pre>
  1299. var Notes = Backbone.Collection.extend({
  1300. url: '/notes'
  1301. });
  1302. // Or, something more sophisticated:
  1303. var Notes = Backbone.Collection.extend({
  1304. url: function() {
  1305. return this.document.url() + '/notes';
  1306. }
  1307. });
  1308. </pre>
  1309. <p id="Collection-parse">
  1310. <b class="header">parse</b><code>collection.parse(response)</code>
  1311. <br />
  1312. <b>parse</b> is called by Backbone whenever a collection's models are
  1313. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1314. The function is passed the raw <tt>response</tt> object, and should return
  1315. the array of model attributes to be <a href="#Collection-add">added</a>
  1316. to the collection. The default implementation is a no-op, simply passing
  1317. through the JSON response. Override this if you need to work with a
  1318. preexisting API, or better namespace your responses. Note that afterwards,
  1319. if your model class already has a <tt>parse</tt> function, it will be
  1320. run against each fetched model.
  1321. </p>
  1322. <pre>
  1323. var Tweets = Backbone.Collection.extend({
  1324. // The Twitter Search API returns tweets under "results".
  1325. parse: function(response) {
  1326. return response.results;
  1327. }
  1328. });
  1329. </pre>
  1330. <p id="Collection-fetch">
  1331. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1332. <br />
  1333. Fetch the default set of models for this collection from the server,
  1334. resetting the collection when they arrive. The <b>options</b> hash takes
  1335. <tt>success</tt> and <tt>error</tt>
  1336. callbacks which will be passed <tt>(collection, response)</tt> as arguments.
  1337. When the model data returns from the server, the collection will
  1338. <a href="#Collection-reset">reset</a>.
  1339. Delegates to <a href="#Sync">Backbone.sync</a>
  1340. under the covers, for custom persistence strategies.
  1341. The server handler for <b>fetch</b> requests should return a JSON array of
  1342. models.
  1343. </p>
  1344. <pre class="runnable">
  1345. Backbone.sync = function(method, model) {
  1346. alert(method + ": " + model.url);
  1347. };
  1348. var Accounts = new Backbone.Collection;
  1349. Accounts.url = '/accounts';
  1350. Accounts.fetch();
  1351. </pre>
  1352. <p>
  1353. If you'd like to add the incoming models to the current collection, instead
  1354. of replacing the collection's contents, pass <tt>{add: true}</tt> as an
  1355. option to <b>fetch</b>.
  1356. </p>
  1357. <p>
  1358. <b>jQuery.ajax</b> options can also be passed directly as <b>fetch</b> options,
  1359. so to fetch a specific page of a paginated collection:
  1360. <tt>Documents.fetch({data: {page: 3}})</tt>
  1361. </p>
  1362. <p>
  1363. Note that <b>fetch</b> should not be used to populate collections on
  1364. page load &mdash; all models needed at load time should already be
  1365. <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
  1366. intended for lazily-loading models for interfaces that are not needed
  1367. immediately: for example, documents with collections of notes that may be
  1368. toggled open and closed.
  1369. </p>
  1370. <p id="Collection-reset">
  1371. <b class="header">reset</b><code>collection.reset(models, [options])</code>
  1372. <br />
  1373. Adding and removing models one at a time is all well and good, but sometimes
  1374. you have so many models to change that you'd rather just update the collection
  1375. in bulk. Use <b>reset</b> to replace a collection with a new list
  1376. of models (or attribute hashes), triggering a single <tt>"reset"</tt> event
  1377. at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"reset"</tt> event.
  1378. Using reset with no arguments is useful as a way to empty the collection.
  1379. </p>
  1380. <p>
  1381. Here's an example using <b>reset</b> to bootstrap a collection during initial page load,
  1382. in a Rails application.
  1383. </p>
  1384. <pre>
  1385. &lt;script&gt;
  1386. Accounts.reset(&lt;%= @accounts.to_json %&gt;);
  1387. &lt;/script&gt;
  1388. </pre>
  1389. <p>
  1390. Calling <tt>collection.reset()</tt> without passing any models as arguments
  1391. will empty the entire collection.
  1392. </p>
  1393. <p id="Collection-create">
  1394. <b class="header">create</b><code>collection.create(attributes, [options])</code>
  1395. <br />
  1396. Convenience to create a new instance of a model within a collection.
  1397. Equivalent to instantiating a model with a hash of attributes,
  1398. saving the model to the server, and adding the model to the set after being
  1399. successfully created. Returns
  1400. the model, or <tt>false</tt> if a validation error prevented the
  1401. model from being created. In order for this to work, you should set the
  1402. <a href="#Collection-model">model</a> property of the collection.
  1403. The <b>create</b> method can accept either an attributes hash or an
  1404. existing, unsaved model object.
  1405. </p>
  1406. <p>
  1407. Creating a model will cause an immediate <tt>"add"</tt> event to be
  1408. triggered on the collection, as well as a <tt>"sync"</tt> event, once the
  1409. model has been successfully created on the server. Pass <tt>{wait: true}</tt>
  1410. if you'd like to wait for the server before adding the new model to the collection.
  1411. </p>
  1412. <pre>
  1413. var Library = Backbone.Collection.extend({
  1414. model: Book
  1415. });
  1416. var NYPL = new Library;
  1417. var othello = NYPL.create({
  1418. title: "Othello",
  1419. author: "William Shakespeare"
  1420. });
  1421. </pre>
  1422. <h2 id="Router">Backbone.Router</h2>
  1423. <p>
  1424. Web applications often provide linkable, bookmarkable, shareable URLs for
  1425. important locations in the app. Until recently, hash fragments
  1426. (<tt>#page</tt>) were used to provide these permalinks, but with the
  1427. arrival of the History API, it's now possible to use standard URLs (<tt>/page</tt>).
  1428. <b>Backbone.Router</b> provides methods for routing client-side pages, and
  1429. connecting them to actions and events. For browsers which don't yet support
  1430. the History API, the Router handles graceful fallback and transparent
  1431. translation to the fragment version of the URL.
  1432. </p>
  1433. <p>
  1434. During page load, after your application has finished creating all of its routers,
  1435. be sure to call <tt>Backbone.history.start()</tt>, or
  1436. <tt>Backbone.history.start({pushState: true})</tt> to route the initial URL.
  1437. </p>
  1438. <p id="Router-extend">
  1439. <b class="header">extend</b><code>Backbone.Router.extend(properties, [classProperties])</code>
  1440. <br />
  1441. Get started by creating a custom router class. Define actions that are
  1442. triggered when certain URL fragments are
  1443. matched, and provide a <a href="#Router-routes">routes</a> hash
  1444. that pairs routes to actions. Note that you'll want to avoid using a
  1445. leading slash in your route definitions:
  1446. </p>
  1447. <pre>
  1448. var Workspace = Backbone.Router.extend({
  1449. routes: {
  1450. "help": "help", // #help
  1451. "search/:query": "search", // #search/kiwis
  1452. "search/:query/p:page": "search" // #search/kiwis/p7
  1453. },
  1454. help: function() {
  1455. ...
  1456. },
  1457. search: function(query, page) {
  1458. ...
  1459. }
  1460. });
  1461. </pre>
  1462. <p id="Router-routes">
  1463. <b class="header">routes</b><code>router.routes</code>
  1464. <br />
  1465. The routes hash maps URLs with parameters to functions on your router,
  1466. similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
  1467. Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
  1468. component between slashes; and splat parts <tt>*splat</tt>, which can match
  1469. any number of URL components.
  1470. </p>
  1471. <p>
  1472. For example, a route of <tt>"search/:query/p:page"</tt> will match
  1473. a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt>
  1474. and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will
  1475. match <tt>#file/nested/folder/file.txt</tt>,
  1476. passing <tt>"nested/folder/file.txt"</tt> to the action.
  1477. </p>
  1478. <p>
  1479. When the visitor presses the back button, or enters a URL, and a particular
  1480. route is matched, the name of the action will be fired as an
  1481. <a href="#Events">event</a>, so that other objects can listen to the router,
  1482. and be notified. In the following example, visiting <tt>#help/uploading</tt>
  1483. will fire a <tt>route:help</tt> event from the router.
  1484. </p>
  1485. <pre>
  1486. routes: {
  1487. "help/:page": "help",
  1488. "download/*path": "download",
  1489. "folder/:name": "openFolder",
  1490. "folder/:name-:mode": "openFolder"
  1491. }
  1492. </pre>
  1493. <pre>
  1494. router.on("route:help", function(page) {
  1495. ...
  1496. });
  1497. </pre>
  1498. <p id="Router-constructor">
  1499. <b class="header">constructor / initialize</b><code>new Router([options])</code>
  1500. <br />
  1501. When creating a new router, you may pass its
  1502. <a href="#Router-routes">routes</a> hash directly as an option, if you
  1503. choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt>
  1504. function, if defined.
  1505. </p>
  1506. <p id="Router-route">
  1507. <b class="header">route</b><code>router.route(route, name, [callback])</code>
  1508. <br />
  1509. Manually create a route for the router, The <tt>route</tt> argument may
  1510. be a <a href="#Router-routes">routing string</a> or regular expression.
  1511. Each matching capture from the route or regular expression will be passed as
  1512. an argument to the callback. The <tt>name</tt> argument will be triggered as
  1513. a <tt>"route:name"</tt> event whenever the route is matched. If the
  1514. <tt>callback</tt> argument is omitted <tt>router[name]</tt> wil