PageRenderTime 95ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

https://github.com/jetleigh/backbone
HTML | 3036 lines | 2597 code | 439 blank | 0 comment | 0 complexity | c41c0c28aa6506b7e5577a2ac199b36a MD5 | raw file

Large files files are truncated, but you can click here to view the full 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. <title>Backbone.js</title>
  7. <style>
  8. body {
  9. font-size: 14px;
  10. line-height: 22px;
  11. font-family: Helvetica Neue, Helvetica, Arial;
  12. background: #f4f4f4 url(docs/images/background.png);
  13. }
  14. .interface {
  15. font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
  16. }
  17. div#sidebar {
  18. background: #fff;
  19. position: fixed;
  20. top: 0; left: 0; bottom: 0;
  21. width: 200px;
  22. overflow-y: auto;
  23. overflow-x: hidden;
  24. padding: 15px 0 30px 30px;
  25. border-right: 1px solid #bbb;
  26. box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
  27. }
  28. a.toc_title, a.toc_title:visited {
  29. display: block;
  30. color: black;
  31. font-weight: bold;
  32. margin-top: 15px;
  33. }
  34. a.toc_title:hover {
  35. text-decoration: underline;
  36. }
  37. #sidebar .version {
  38. font-size: 10px;
  39. font-weight: normal;
  40. }
  41. ul.toc_section {
  42. font-size: 11px;
  43. line-height: 14px;
  44. margin: 5px 0 0 0;
  45. padding-left: 0px;
  46. list-style-type: none;
  47. font-family: Lucida Grande;
  48. }
  49. .toc_section li {
  50. cursor: pointer;
  51. margin: 0 0 3px 0;
  52. }
  53. .toc_section li a {
  54. text-decoration: none;
  55. color: black;
  56. }
  57. .toc_section li a:hover {
  58. text-decoration: underline;
  59. }
  60. div.container {
  61. position: relative;
  62. width: 550px;
  63. margin: 40px 0 50px 260px;
  64. }
  65. div.run {
  66. position: absolute;
  67. right: 15px;
  68. width: 26px; height: 18px;
  69. background: url('docs/images/arrows.png') no-repeat -26px 0;
  70. }
  71. div.run:active {
  72. background-position: -51px 0;
  73. }
  74. p, div.container ul {
  75. margin: 20px 0;
  76. width: 550px;
  77. }
  78. p.warning {
  79. font-size: 12px;
  80. line-height: 18px;
  81. font-style: italic;
  82. }
  83. div.container ul {
  84. list-style: circle;
  85. font-size: 12px;
  86. padding-left: 15px;
  87. }
  88. a, a:visited {
  89. color: #444;
  90. }
  91. a:active, a:hover {
  92. color: #000;
  93. }
  94. a img {
  95. border: 0;
  96. }
  97. h1, h2, h3, h4, h5, h6 {
  98. padding-top: 20px;
  99. }
  100. h2 {
  101. font-size: 20px;
  102. }
  103. b.header {
  104. font-size: 16px;
  105. line-height: 30px;
  106. }
  107. span.alias {
  108. font-size: 14px;
  109. font-style: italic;
  110. margin-left: 20px;
  111. }
  112. table {
  113. margin: 15px 0 0; padding: 0;
  114. }
  115. tr, td {
  116. margin: 0; padding: 0;
  117. }
  118. td {
  119. padding: 0px 15px 5px 0;
  120. }
  121. code, pre, tt {
  122. font-family: Monaco, Consolas, "Lucida Console", monospace;
  123. font-size: 12px;
  124. line-height: 18px;
  125. font-style: normal;
  126. }
  127. tt {
  128. padding: 0px 3px;
  129. background: #fff;
  130. border: 1px solid #ddd;
  131. zoom: 1;
  132. }
  133. code {
  134. margin-left: 20px;
  135. }
  136. pre {
  137. font-size: 12px;
  138. padding: 2px 0 2px 15px;
  139. border: 4px solid #bbb; border-top: 0; border-bottom: 0;
  140. margin: 0px 0 30px;
  141. }
  142. img.example_image {
  143. margin: 0px auto;
  144. }
  145. </style>
  146. </head>
  147. <body>
  148. <div id="sidebar" class="interface">
  149. <a class="toc_title" href="#">
  150. Backbone.js <span class="version">(0.5.3)</span>
  151. </a>
  152. <a class="toc_title" href="#Introduction">
  153. Introduction
  154. </a>
  155. <a class="toc_title" href="#Events">
  156. Events
  157. </a>
  158. <ul class="toc_section">
  159. <li> <a href="#Events-bind">bind</a></li>
  160. <li> <a href="#Events-unbind">unbind</a></li>
  161. <li> <a href="#Events-trigger">trigger</a></li>
  162. </ul>
  163. <a class="toc_title" href="#Model">
  164. Model
  165. </a>
  166. <ul class="toc_section">
  167. <li> <a href="#Model-extend">extend</a></li>
  168. <li> <a href="#Model-constructor">constructor / initialize</a></li>
  169. <li> <a href="#Model-get">get</a></li>
  170. <li> <a href="#Model-set">set</a></li>
  171. <li> <a href="#Model-escape">escape</a></li>
  172. <li> <a href="#Model-has">has</a></li>
  173. <li> <a href="#Model-unset">unset</a></li>
  174. <li> <a href="#Model-clear">clear</a></li>
  175. <li> <a href="#Model-id">id</a></li>
  176. <li> <a href="#Model-idAttribute">idAttribute</a></li>
  177. <li> <a href="#Model-cid">cid</a></li>
  178. <li> <a href="#Model-attributes">attributes</a></li>
  179. <li> <a href="#Model-defaults">defaults</a></li>
  180. <li>- <a href="#Model-toJSON">toJSON</a></li>
  181. <li> <a href="#Model-fetch">fetch</a></li>
  182. <li> <a href="#Model-save">save</a></li>
  183. <li> <a href="#Model-destroy">destroy</a></li>
  184. <li> <a href="#Model-validate">validate</a></li>
  185. <li> <a href="#Model-url">url</a></li>
  186. <li> <a href="#Model-urlRoot">urlRoot</a></li>
  187. <li> <a href="#Model-parse">parse</a></li>
  188. <li> <a href="#Model-clone">clone</a></li>
  189. <li> <a href="#Model-isNew">isNew</a></li>
  190. <li> <a href="#Model-change">change</a></li>
  191. <li> <a href="#Model-hasChanged">hasChanged</a></li>
  192. <li> <a href="#Model-changedAttributes">changedAttributes</a></li>
  193. <li> <a href="#Model-previous">previous</a></li>
  194. <li> <a href="#Model-previousAttributes">previousAttributes</a></li>
  195. </ul>
  196. <a class="toc_title" href="#Collection">
  197. Collection
  198. </a>
  199. <ul class="toc_section">
  200. <li> <a href="#Collection-extend">extend</a></li>
  201. <li> <a href="#Collection-model">model</a></li>
  202. <li> <a href="#Collection-constructor">constructor / initialize</a></li>
  203. <li> <a href="#Collection-models">models</a></li>
  204. <li> <a href="#Collection-toJSON">toJSON</a></li>
  205. <li> <a href="#Collection-Underscore-Methods"><b>Underscore Methods (26)</b></a></li>
  206. <li> <a href="#Collection-add">add</a></li>
  207. <li> <a href="#Collection-remove">remove</a></li>
  208. <li> <a href="#Collection-get">get</a></li>
  209. <li> <a href="#Collection-getByCid">getByCid</a></li>
  210. <li> <a href="#Collection-at">at</a></li>
  211. <li> <a href="#Collection-length">length</a></li>
  212. <li> <a href="#Collection-comparator">comparator</a></li>
  213. <li> <a href="#Collection-sort">sort</a></li>
  214. <li> <a href="#Collection-pluck">pluck</a></li>
  215. <li> <a href="#Collection-url">url</a></li>
  216. <li> <a href="#Collection-parse">parse</a></li>
  217. <li> <a href="#Collection-fetch">fetch</a></li>
  218. <li> <a href="#Collection-reset">reset</a></li>
  219. <li> <a href="#Collection-create">create</a></li>
  220. </ul>
  221. <a class="toc_title" href="#Router">
  222. Router
  223. </a>
  224. <ul class="toc_section">
  225. <li> <a href="#Router-extend">extend</a></li>
  226. <li> <a href="#Router-routes">routes</a></li>
  227. <li> <a href="#Router-constructor">constructor / initialize</a></li>
  228. <li> <a href="#Router-route">route</a></li>
  229. <li> <a href="#Router-navigate">navigate</a></li>
  230. </ul>
  231. <a class="toc_title" href="#History">
  232. History
  233. </a>
  234. <ul class="toc_section">
  235. <li> <a href="#History-start">start</a></li>
  236. </ul>
  237. <a class="toc_title" href="#Sync">
  238. Sync
  239. </a>
  240. <ul class="toc_section">
  241. <li> <a href="#Sync">Backbone.sync</a></li>
  242. <li> <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li>
  243. <li> <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li>
  244. </ul>
  245. <a class="toc_title" href="#View">
  246. View
  247. </a>
  248. <ul class="toc_section">
  249. <li> <a href="#View-extend">extend</a></li>
  250. <li> <a href="#View-constructor">constructor / initialize</a></li>
  251. <li> <a href="#View-el">el</a></li>
  252. <li> <a href="#View-dollar">$ (jQuery or Zepto)</a></li>
  253. <li> <a href="#View-render">render</a></li>
  254. <li> <a href="#View-remove">remove</a></li>
  255. <li> <a href="#View-make">make</a></li>
  256. <li> <a href="#View-delegateEvents">delegateEvents</a></li>
  257. </ul>
  258. <a class="toc_title" href="#Utility">
  259. Utility
  260. </a>
  261. <ul class="toc_section">
  262. <li> <a href="#Utility-noConflict">noConflict</a></li>
  263. </ul>
  264. <a class="toc_title" href="#examples">
  265. Examples
  266. </a>
  267. <ul class="toc_section">
  268. <li> <a href="#examples-todos">Todos</a></li>
  269. <li> <a href="#examples-documentcloud">DocumentCloud</a></li>
  270. <li> <a href="#examples-linkedin">LinkedIn Mobile</a></li>
  271. <li> <a href="#examples-flow">Flow</a></li>
  272. <li> <a href="#examples-audiovroom">AudioVroom</a></li>
  273. <li> <a href="#examples-foursquare">Foursquare</a></li>
  274. <li> <a href="#examples-do">Do</a></li>
  275. <li> <a href="#examples-posterous">Posterous Spaces</a></li>
  276. <li> <a href="#examples-groupon">Groupon Now!</a></li>
  277. <li> <a href="#examples-basecamp">Basecamp Mobile</a></li>
  278. <li> <a href="#examples-slavery-footprint">Slavery Footprint</a></li>
  279. <li> <a href="#examples-diaspora">Diaspora</a></li>
  280. <li> <a href="#examples-trajectory">Trajectory</a></li>
  281. <li> <a href="#examples-soundcloud">SoundCloud Mobile</a></li>
  282. <li> <a href="#examples-pandora">Pandora</a></li>
  283. <li> <a href="#examples-cloudapp">CloudApp</a></li>
  284. <li> <a href="#examples-seatgeek">SeatGeek</a></li>
  285. <li> <a href="#examples-grove">Grove.io</a></li>
  286. <li> <a href="#examples-kicksend">Kicksend</a></li>
  287. <li> <a href="#examples-shortmail">Shortmail</a></li>
  288. <li> <a href="#examples-battlefield">Battlefield Play4Free</a></li>
  289. <li> <a href="#examples-salon">Salon.io</a></li>
  290. <li> <a href="#examples-quoteroller">Quote Roller</a></li>
  291. <li> <a href="#examples-tilemill">TileMill</a></li>
  292. <li> <a href="#examples-rround">rround.me</a></li>
  293. <li>- <a href="#examples-blossom">Blossom</a></li>
  294. <li>- <a href="#examples-instagreat">Insta-great!</a></li>
  295. <li>- <a href="#examples-decide">Decide</a></li>
  296. <li>- <a href="#examples-trello">Trello</a></li>
  297. <li>- <a href="#examples-bittorrent">BitTorrent</a></li>
  298. <li>- <a href="#examples-picplum">Picplum</a></li>
  299. <li>- <a href="#examples-ducksboard">Ducksboard</a></li>
  300. <li>- <a href="#examples-quietwrite">QuietWrite</a></li>
  301. <li>- <a href="#examples-tzigla">Tzigla</a></li>
  302. </ul>
  303. <a class="toc_title" href="#faq">
  304. F.A.Q.
  305. </a>
  306. <ul class="toc_section">
  307. <li> <a href="#FAQ-events">Catalog of Events</a></li>
  308. <li> <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li>
  309. <li> <a href="#FAQ-nested">Nested Models &amp; Collections</a></li>
  310. <li> <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li>
  311. <li> <a href="#FAQ-mvc">Traditional MVC</a></li>
  312. <li> <a href="#FAQ-this">Binding "this"</a></li>
  313. </ul>
  314. <a class="toc_title" href="#changelog">
  315. Change Log
  316. </a>
  317. </div>
  318. <div class="container">
  319. <p>
  320. <img style="width: 451px; height: 80px;" src="docs/images/backbone.png" alt="Backbone.js" />
  321. </p>
  322. <p>
  323. <a href="http://github.com/documentcloud/backbone/">Backbone</a>
  324. supplies structure to JavaScript-heavy applications by providing <b>models</b> with
  325. key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
  326. <b>views</b> with declarative event handling, and connects it all to your
  327. existing application over a RESTful JSON interface.
  328. </p>
  329. <p>
  330. The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
  331. and the <a href="docs/backbone.html">annotated source code</a> is available,
  332. as well as an online <a href="test/test.html">test suite</a>, an
  333. <a href="examples/todos/index.html">example application</a> and a
  334. <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a>.
  335. </p>
  336. <p>
  337. You can report bugs and discuss features on the
  338. <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>,
  339. on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the
  340. <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>,
  341. or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>.
  342. </p>
  343. <p>
  344. <i>
  345. Backbone is an open-source component of
  346. <a href="http://documentcloud.org/">DocumentCloud</a>.
  347. </i>
  348. </p>
  349. <h2 id="downloads">
  350. Downloads &amp; Dependencies
  351. <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
  352. </h2>
  353. <table>
  354. <tr>
  355. <td><a href="backbone.js">Development Version (0.5.3)</a></td>
  356. <td><i>41kb, Full Source with Comments</i></td>
  357. </tr>
  358. <tr>
  359. <td><a href="backbone-min.js">Production Version (0.5.3)</a></td>
  360. <td><i>4.6kb, Packed and Gzipped</i></td>
  361. </tr>
  362. </table>
  363. <p>
  364. Backbone's only hard dependency is
  365. <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
  366. For RESTful persistence, history support via <a href="#Router">Backbone.Router</a>
  367. and DOM manipulation with <a href="#View">Backbone.View</a>, include
  368. <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either
  369. <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or
  370. <a href="http://zeptojs.com/">Zepto</a>.
  371. </p>
  372. <h2 id="Introduction">Introduction</h2>
  373. <p>
  374. When working on a web application that involves a lot of JavaScript, one
  375. of the first things you learn is to stop tying your data to the DOM. It's all
  376. too easy to create JavaScript applications that end up as tangled piles of
  377. jQuery selectors and callbacks, all trying frantically to keep data in
  378. sync between the HTML UI, your JavaScript logic, and the database on your
  379. server. For rich client-side applications, a more structured approach
  380. is often helpful.
  381. </p>
  382. <p>
  383. With Backbone, you represent your data as
  384. <a href="#Model">Models</a>, which can be created, validated, destroyed,
  385. and saved to the server. Whenever a UI action causes an attribute of
  386. a model to change, the model triggers a <i>"change"</i> event; all
  387. the <a href="#View">Views</a> that display the model's state can be notified of the
  388. change, so that they are able to respond accordingly, re-rendering themselves with
  389. the new information. In a finished Backbone app, you don't have to write the glue
  390. code that looks into the DOM to find an element with a specific <i>id</i>,
  391. and update the HTML manually
  392. &mdash; when the model changes, the views simply update themselves.
  393. </p>
  394. <p>
  395. Many of the examples that follow are runnable. Click the <i>play</i> button
  396. to execute them.
  397. </p>
  398. <h2 id="Events">Backbone.Events</h2>
  399. <p>
  400. <b>Events</b> is a module that can be mixed in to any object, giving the
  401. object the ability to bind and trigger custom named events. Events do not
  402. have to be declared before they are bound, and may take passed arguments.
  403. For example:
  404. </p>
  405. <pre class="runnable">
  406. var object = {};
  407. _.extend(object, Backbone.Events);
  408. object.bind("alert", function(msg) {
  409. alert("Triggered " + msg);
  410. });
  411. object.trigger("alert", "an event");
  412. </pre>
  413. <p id="Events-bind">
  414. <b class="header">bind</b><code>object.bind(event, callback, [context])</code>
  415. <br />
  416. Bind a <b>callback</b> function to an object. The callback will be invoked
  417. whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
  418. If you have a large number of different events on a page, the convention is to use colons to
  419. namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
  420. </p>
  421. <p>
  422. To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked,
  423. pass the optional third argument: <tt>model.bind('change', this.render, this)</tt>
  424. </p>
  425. <p>
  426. Callbacks bound to the special
  427. <tt>"all"</tt> event will be triggered when any event occurs, and are passed
  428. the name of the event as the first argument. For example, to proxy all events
  429. from one object to another:
  430. </p>
  431. <pre>
  432. proxy.bind("all", function(eventName) {
  433. object.trigger(eventName);
  434. });
  435. </pre>
  436. <p id="Events-unbind">
  437. <b class="header">unbind</b><code>object.unbind([event], [callback])</code>
  438. <br />
  439. Remove a previously-bound <b>callback</b> function from an object. If no
  440. callback is specified, all callbacks for the <b>event</b> will be
  441. removed. If no event is specified, <i>all</i> event callbacks on the object
  442. will be removed.
  443. </p>
  444. <pre>
  445. object.unbind("change", onChange); // Removes just the onChange callback.
  446. object.unbind("change"); // Removes all "change" callbacks.
  447. object.unbind(); // Removes all callbacks on object.
  448. </pre>
  449. <p id="Events-trigger">
  450. <b class="header">trigger</b><code>object.trigger(event, [*args])</code>
  451. <br />
  452. Trigger callbacks for the given <b>event</b>. Subsequent arguments to
  453. <b>trigger</b> will be passed along to the event callbacks.
  454. </p>
  455. <h2 id="Model">Backbone.Model</h2>
  456. <p>
  457. <b>Models</b> are the heart of any JavaScript application, containing
  458. the interactive data as well as a large part of the logic surrounding it:
  459. conversions, validations, computed properties, and access control. You
  460. extend <b>Backbone.Model</b> with your domain-specific methods, and
  461. <b>Model</b> provides a basic set of functionality for managing changes.
  462. </p>
  463. <p>
  464. The following is a contrived example, but it demonstrates defining a model
  465. with a custom method, setting an attribute, and firing an event keyed
  466. to changes in that specific attribute.
  467. After running this code once, <tt>sidebar</tt> will be
  468. available in your browser's console, so you can play around with it.
  469. </p>
  470. <pre class="runnable">
  471. var Sidebar = Backbone.Model.extend({
  472. promptColor: function() {
  473. var cssColor = prompt("Please enter a CSS color:");
  474. this.set({color: cssColor});
  475. }
  476. });
  477. window.sidebar = new Sidebar;
  478. sidebar.bind('change:color', function(model, color) {
  479. $('#sidebar').css({background: color});
  480. });
  481. sidebar.set({color: 'white'});
  482. sidebar.promptColor();
  483. </pre>
  484. <p id="Model-extend">
  485. <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
  486. <br />
  487. To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
  488. and provide instance <b>properties</b>, as well as optional
  489. <b>classProperties</b> to be attached directly to the constructor function.
  490. </p>
  491. <p>
  492. <b>extend</b> correctly sets up the prototype chain, so subclasses created
  493. with <b>extend</b> can be further extended and subclassed as far as you like.
  494. </p>
  495. <pre>
  496. var Note = Backbone.Model.extend({
  497. initialize: function() { ... },
  498. author: function() { ... },
  499. coordinates: function() { ... },
  500. allowedToEdit: function(account) {
  501. return true;
  502. }
  503. });
  504. var PrivateNote = Note.extend({
  505. allowedToEdit: function(account) {
  506. return account.owns(this);
  507. }
  508. });
  509. </pre>
  510. <p class="warning">
  511. Brief aside on <tt>super</tt>: JavaScript does not provide
  512. a simple way to call super &mdash; the function of the same name defined
  513. higher on the prototype chain. If you override a core function like
  514. <tt>set</tt>, or <tt>save</tt>, and you want to invoke the
  515. parent object's implementation, you'll have to explicitly call it, along these lines:
  516. </p>
  517. <pre>
  518. var Note = Backbone.Model.extend({
  519. set: function(attributes, options) {
  520. Backbone.Model.prototype.set.call(this, attributes, options);
  521. ...
  522. }
  523. });
  524. </pre>
  525. <p id="Model-constructor">
  526. <b class="header">constructor / initialize</b><code>new Model([attributes])</code>
  527. <br />
  528. When creating an instance of a model, you can pass in the initial values
  529. of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
  530. model. If you define an <b>initialize</b> function, it will be invoked when
  531. the model is created.
  532. </p>
  533. <pre>
  534. new Book({
  535. title: "One Thousand and One Nights",
  536. author: "Scheherazade"
  537. });
  538. </pre>
  539. <p id="Model-get">
  540. <b class="header">get</b><code>model.get(attribute)</code>
  541. <br />
  542. Get the current value of an attribute from the model. For example:
  543. <tt>note.get("title")</tt>
  544. </p>
  545. <p id="Model-set">
  546. <b class="header">set</b><code>model.set(attributes, [options])</code>
  547. <br />
  548. Set a hash of attributes (one or many) on the model. If any of the attributes
  549. change the models state, a <tt>"change"</tt> event will be triggered, unless
  550. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  551. attributes are also triggered, and you can bind to those as well, for example:
  552. <tt>change:title</tt>, and <tt>change:content</tt>.
  553. </p>
  554. <pre>
  555. note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
  556. </pre>
  557. <p>
  558. If the model has a <a href="#Model-validate">validate</a> method,
  559. it will be validated before the attributes are set, no changes will
  560. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  561. Otherwise, <b>set</b> returns a reference to the model.
  562. You may also pass an <tt>error</tt>
  563. callback in the options, which will be invoked instead of triggering an
  564. <tt>"error"</tt> event, should validation fail.
  565. </p>
  566. <p id="Model-escape">
  567. <b class="header">escape</b><code>model.escape(attribute)</code>
  568. <br />
  569. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  570. of a model's attribute. If you're interpolating data from the model into
  571. HTML, using <b>escape</b> to retrieve attributes will prevent
  572. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  573. </p>
  574. <pre class="runnable">
  575. var hacker = new Backbone.Model({
  576. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  577. });
  578. alert(hacker.escape('name'));
  579. </pre>
  580. <p id="Model-has">
  581. <b class="header">has</b><code>model.has(attribute)</code>
  582. <br />
  583. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  584. value.
  585. </p>
  586. <pre>
  587. if (note.has("title")) {
  588. ...
  589. }
  590. </pre>
  591. <p id="Model-unset">
  592. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  593. <br />
  594. Remove an attribute by deleting it from the internal attributes hash.
  595. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  596. </p>
  597. <p id="Model-clear">
  598. <b class="header">clear</b><code>model.clear([options])</code>
  599. <br />
  600. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  601. <tt>silent</tt> is passed as an option.
  602. </p>
  603. <p id="Model-id">
  604. <b class="header">id</b><code>model.id</code>
  605. <br />
  606. A special property of models, the <b>id</b> is an arbitrary string
  607. (integer id or UUID). If you set the <b>id</b> in the
  608. attributes hash, it will be copied onto the model as a direct property.
  609. Models can be retrieved by id from collections, and the id is used to generate
  610. model URLs by default.
  611. </p>
  612. <p id="Model-idAttribute">
  613. <b class="header">idAttribute</b><code>model.idAttribute</code>
  614. <br />
  615. A model's unique identifier is stored under the <tt>id</tt> attribute.
  616. If you're directly communicating with a backend (CouchDB, MongoDB) that uses
  617. a different unique key, you may set a Model's <tt>idAttribute</tt> to
  618. transparently map from that key to <tt>id</tt>.
  619. <pre class="runnable">
  620. var Meal = Backbone.Model.extend({
  621. idAttribute: "_id"
  622. });
  623. var cake = new Meal({ _id: 1, name: "Cake" });
  624. alert("Cake id: " + cake.id);
  625. </pre>
  626. </p>
  627. <p id="Model-cid">
  628. <b class="header">cid</b><code>model.cid</code>
  629. <br />
  630. A special property of models, the <b>cid</b> or client id is a unique identifier
  631. automatically assigned to all models when they're first created. Client ids
  632. are handy when the model has not yet been saved to the server, and does not
  633. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  634. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  635. </p>
  636. <p id="Model-attributes">
  637. <b class="header">attributes</b><code>model.attributes</code>
  638. <br />
  639. The <b>attributes</b> property is the internal hash containing the model's
  640. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  641. them directly. If you'd like to retrieve and munge a copy of the model's
  642. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  643. </p>
  644. <p id="Model-defaults">
  645. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  646. <br />
  647. The <b>defaults</b> hash (or function) can be used to specify the default
  648. attributes for your model. When creating an instance of the model,
  649. any unspecified attributes will be set to their default value.
  650. </p>
  651. <pre class="runnable">
  652. var Meal = Backbone.Model.extend({
  653. defaults: {
  654. "appetizer": "caesar salad",
  655. "entree": "ravioli",
  656. "dessert": "cheesecake"
  657. }
  658. });
  659. alert("Dessert will be " + (new Meal).get('dessert'));
  660. </pre>
  661. <p class="warning">
  662. Remember that in JavaScript, objects are passed by reference, so if you
  663. include an object as a default value, it will be shared among all instances.
  664. </p>
  665. <p id="Model-toJSON">
  666. <b class="header">toJSON</b><code>model.toJSON()</code>
  667. <br />
  668. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  669. This can be used for persistence, serialization, or for augmentation before
  670. being handed off to a view. The name of this method is a bit confusing, as
  671. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  672. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  673. </p>
  674. <pre class="runnable">
  675. var artist = new Backbone.Model({
  676. firstName: "Wassily",
  677. lastName: "Kandinsky"
  678. });
  679. artist.set({birthday: "December 16, 1866"});
  680. alert(JSON.stringify(artist));
  681. </pre>
  682. <p id="Model-fetch">
  683. <b class="header">fetch</b><code>model.fetch([options])</code>
  684. <br />
  685. Resets the model's state from the server. Useful if the model has never
  686. been populated with data, or if you'd like to ensure that you have the
  687. latest server state. A <tt>"change"</tt> event will be triggered if the
  688. server's state differs from the current attributes. Accepts
  689. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  690. are passed <tt>(model, response)</tt> as arguments.
  691. </p>
  692. <pre>
  693. // Poll every 10 seconds to keep the channel model up-to-date.
  694. setInterval(function() {
  695. channel.fetch();
  696. }, 10000);
  697. </pre>
  698. <p id="Model-save">
  699. <b class="header">save</b><code>model.save([attributes], [options])</code>
  700. <br />
  701. Save a model to your database (or alternative persistence layer),
  702. by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
  703. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  704. you'd like to change -- keys that aren't mentioned won't be altered.
  705. If the model has a <a href="#Model-validate">validate</a>
  706. method, and validation fails, the model will not be saved. If the model
  707. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  708. (HTTP <tt>POST</tt>), if the model already
  709. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  710. </p>
  711. <p>
  712. In the following example, notice how our overridden version
  713. of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request
  714. the first time the model is saved and an <tt>"update"</tt>
  715. request the second time.
  716. </p>
  717. <pre class="runnable">
  718. Backbone.sync = function(method, model) {
  719. alert(method + ": " + JSON.stringify(model));
  720. model.id = 1;
  721. };
  722. var book = new Backbone.Model({
  723. title: "The Rough Riders",
  724. author: "Theodore Roosevelt"
  725. });
  726. book.save();
  727. book.save({author: "Teddy"});
  728. </pre>
  729. <p>
  730. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  731. options hash, which are passed <tt>(model, response)</tt> as arguments.
  732. The <tt>error</tt> callback will also be invoked if the model has a
  733. <tt>validate</tt> method, and validation fails. If a server-side
  734. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  735. an error response in text or JSON.
  736. </p>
  737. <pre>
  738. book.save({author: "F.D.R."}, {error: function(){ ... }});
  739. </pre>
  740. <p id="Model-destroy">
  741. <b class="header">destroy</b><code>model.destroy([options])</code>
  742. <br />
  743. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  744. request to <a href="#Sync">Backbone.sync</a>. Accepts
  745. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  746. Triggers a <tt>"destroy"</tt> event on the model, which will bubble up
  747. through any collections that contain it.
  748. </p>
  749. <pre>
  750. book.destroy({success: function(model, response) {
  751. ...
  752. }});
  753. </pre>
  754. <p id="Model-validate">
  755. <b class="header">validate</b><code>model.validate(attributes)</code>
  756. <br />
  757. This method is left undefined, and you're encouraged to override it with
  758. your custom validation logic, if you have any that can be performed
  759. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  760. <tt>save</tt>, and is passed the attributes that are about to be updated.
  761. If the model and attributes are valid, don't return anything from <b>validate</b>;
  762. if the attributes are invalid, return an error of your choosing. It
  763. can be as simple as a string error message to be displayed, or a complete
  764. error object that describes the error programmatically. <tt>set</tt> and
  765. <tt>save</tt> will not continue if <b>validate</b> returns an error.
  766. Failed validations trigger an <tt>"error"</tt> event.
  767. </p>
  768. <pre class="runnable">
  769. var Chapter = Backbone.Model.extend({
  770. validate: function(attrs) {
  771. if (attrs.end < attrs.start) {
  772. return "can't end before it starts";
  773. }
  774. }
  775. });
  776. var one = new Chapter({
  777. title : "Chapter One: The Beginning"
  778. });
  779. one.bind("error", function(model, error) {
  780. alert(model.get("title") + " " + error);
  781. });
  782. one.set({
  783. start: 15,
  784. end: 10
  785. });
  786. </pre>
  787. <p>
  788. <tt>"error"</tt> events are useful for providing coarse-grained error
  789. messages at the model or collection level, but if you have a specific view
  790. that can better handle the error, you may override and suppress the event
  791. by passing an <tt>error</tt> callback directly:
  792. </p>
  793. <pre>
  794. account.set({access: "unlimited"}, {
  795. error: function(model, error) {
  796. alert(error);
  797. }
  798. });
  799. </pre>
  800. <p id="Model-url">
  801. <b class="header">url</b><code>model.url()</code>
  802. <br />
  803. Returns the relative URL where the model's resource would be located on
  804. the server. If your models are located somewhere else, override this method
  805. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  806. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  807. </p>
  808. <p>
  809. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  810. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  811. property, if all models of this class share a common root URL.
  812. A model with an id of <tt>101</tt>, stored in a
  813. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  814. would have this URL: <tt>"/documents/7/notes/101"</tt>
  815. </p>
  816. <p id="Model-urlRoot">
  817. <b class="header">urlRoot</b><code>model.urlRoot</code>
  818. <br />
  819. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  820. to enable the default <a href="#Model-url">url</a> function to generate
  821. URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
  822. </p>
  823. <pre class="runnable">
  824. var Book = Backbone.Model.extend({urlRoot : '/books'});
  825. var solaris = new Book({id: "1083-lem-solaris"});
  826. alert(solaris.url());
  827. </pre>
  828. <p id="Model-parse">
  829. <b class="header">parse</b><code>model.parse(response)</code>
  830. <br />
  831. <b>parse</b> is called whenever a model's data is returned by the
  832. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  833. The function is passed the raw <tt>response</tt> object, and should return
  834. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  835. default implementation is a no-op, simply passing through the JSON response.
  836. Override this if you need to work with a preexisting API, or better namespace
  837. your responses.
  838. </p>
  839. <p>
  840. If you're working with a Rails backend, you'll notice that Rails' default
  841. <tt>to_json</tt> implementation includes a model's attributes under a
  842. namespace. To disable this behavior for seamless Backbone integration, set:
  843. </p>
  844. <pre>
  845. ActiveRecord::Base.include_root_in_json = false
  846. </pre>
  847. <p id="Model-clone">
  848. <b class="header">clone</b><code>model.clone()</code>
  849. <br />
  850. Returns a new instance of the model with identical attributes.
  851. </p>
  852. <p id="Model-isNew">
  853. <b class="header">isNew</b><code>model.isNew()</code>
  854. <br />
  855. Has this model been saved to the server yet? If the model does not yet have
  856. an <tt>id</tt>, it is considered to be new.
  857. </p>
  858. <p id="Model-change">
  859. <b class="header">change</b><code>model.change()</code>
  860. <br />
  861. Manually trigger the <tt>"change"</tt> event.
  862. If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  863. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  864. when you're all finished.
  865. </p>
  866. <p id="Model-hasChanged">
  867. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  868. <br />
  869. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  870. is passed, returns <tt>true</tt> if that specific attribute has changed.
  871. </p>
  872. <p class="warning">
  873. Note that this method, and the following change-related ones,
  874. are only useful during the course of a <tt>"change"</tt> event.
  875. </p>
  876. <pre>
  877. book.bind("change", function() {
  878. if (book.hasChanged("title")) {
  879. ...
  880. }
  881. });
  882. </pre>
  883. <p id="Model-changedAttributes">
  884. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  885. <br />
  886. Retrieve a hash of only the model's attributes that have changed. Optionally,
  887. an external <b>attributes</b> hash can be passed in, returning
  888. the attributes in that hash which differ from the model. This can be used
  889. to figure out which portions of a view should be updated, or what calls
  890. need to be made to sync the changes to the server.
  891. </p>
  892. <p id="Model-previous">
  893. <b class="header">previous</b><code>model.previous(attribute)</code>
  894. <br />
  895. During a <tt>"change"</tt> event, this method can be used to get the
  896. previous value of a changed attribute.
  897. </p>
  898. <pre class="runnable">
  899. var bill = new Backbone.Model({
  900. name: "Bill Smith"
  901. });
  902. bill.bind("change:name", function(model, name) {
  903. alert("Changed name from " + bill.previous("name") + " to " + name);
  904. });
  905. bill.set({name : "Bill Jones"});
  906. </pre>
  907. <p id="Model-previousAttributes">
  908. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  909. <br />
  910. Return a copy of the model's previous attributes. Useful for getting a
  911. diff between versions of a model, or getting back to a valid state after
  912. an error occurs.
  913. </p>
  914. <h2 id="Collection">Backbone.Collection</h2>
  915. <p>
  916. Collections are ordered sets of models. You can bind <tt>"change"</tt> events
  917. to be notified when any model in the collection has been modified,
  918. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  919. the collection from the server, and use a full suite of
  920. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  921. </p>
  922. <p>
  923. Any event that is triggered on a model in a collection will also be
  924. triggered on the collection directly, for convenience.
  925. This allows you to listen for changes to specific attributes in any
  926. model in a collection, for example:
  927. <tt>Documents.bind("change:selected", ...)</tt>
  928. </p>
  929. <p id="Collection-extend">
  930. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  931. <br />
  932. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  933. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  934. directly to the collection's constructor function.
  935. </p>
  936. <p id="Collection-model">
  937. <b class="header">model</b><code>collection.model</code>
  938. <br />
  939. Override this property to specify the model class that the collection
  940. contains. If defined, you can pass raw attributes objects (and arrays) to
  941. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  942. and <a href="#Collection-reset">reset</a>, and the attributes will be
  943. converted into a model of the proper type.
  944. </p>
  945. <pre>
  946. var Library = Backbone.Collection.extend({
  947. model: Book
  948. });
  949. </pre>
  950. <p id="Collection-constructor">
  951. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  952. <br />
  953. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  954. The collection's <a href="#Collection-comparator">comparator</a> function
  955. may be included as an option. If you define an <b>initialize</b> function, it will be
  956. invoked when the collection is created.
  957. </p>
  958. <pre>
  959. var tabs = new TabSet([tab1, tab2, tab3]);
  960. </pre>
  961. <p id="Collection-models">
  962. <b class="header">models</b><code>collection.models</code>
  963. <br />
  964. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  965. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  966. to access model objects, but occasionally a direct reference to the array
  967. is desired.
  968. </p>
  969. <p id="Collection-toJSON">
  970. <b class="header">toJSON</b><code>collection.toJSON()</code>
  971. <br />
  972. Return an array containing the attributes hash of each model in the
  973. collection. This can be used to serialize and persist the
  974. collection as a whole. The name of this method is a bit confusing, because
  975. it conforms to
  976. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  977. </p>
  978. <pre class="runnable">
  979. var collection = new Backbone.Collection([
  980. {name: "Tim", age: 5},
  981. {name: "Ida", age: 26},
  982. {name: "Rob", age: 55}
  983. ]);
  984. alert(JSON.stringify(collection));
  985. </pre>
  986. <p id="Collection-Underscore-Methods">
  987. <b class="header">Underscore Methods (26)</b>
  988. <br />
  989. Backbone proxies to <b>Underscore.js</b> to provide 26 iteration functions
  990. on <b>Backbone.Collection</b>. They aren't all documented here, but
  991. you can take a look at the Underscore documentation for the full details&hellip;
  992. </p>
  993. <ul>
  994. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  995. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  996. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  997. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  998. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  999. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  1000. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  1001. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  1002. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  1003. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  1004. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  1005. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  1006. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  1007. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  1008. <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li>
  1009. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  1010. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  1011. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  1012. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  1013. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  1014. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  1015. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  1016. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  1017. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  1018. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  1019. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  1020. </ul>
  1021. <pre>
  1022. Books.each(function(book) {
  1023. book.publish();
  1024. });
  1025. var titles = Books.map(function(book) {
  1026. return book.get("title");
  1027. });
  1028. var publishedBooks = Books.filter(function(book) {
  1029. return book.get("published") === true;
  1030. });
  1031. var alphabetical = Books.sortBy(function(book) {
  1032. return book.author.get("name").toLowerCase();
  1033. });
  1034. </pre>
  1035. <p id="Collection-add">
  1036. <b class="header">add</b><code>collection.add(models, [options])</code>
  1037. <br />
  1038. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  1039. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  1040. <a href="#Collection-model">model</a> property is defined, you may also pass
  1041. raw attributes objects, and have them be vivified as instances of the model.
  1042. Pass <tt>{at: index}</tt> to splice the model into the collection at the
  1043. specified <tt>index</tt>.
  1044. </p>
  1045. <pre class="runnable">
  1046. var ships = new Backbone.Collection;
  1047. ships.bind("add", function(ship) {
  1048. alert("Ahoy " + ship.get("name") + "!");
  1049. });
  1050. ships.add([
  1051. {name: "Flying Dutchman"},
  1052. {name: "Black Pearl"}
  1053. ]);
  1054. </pre>
  1055. <p id="Collection-remove">
  1056. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  1057. <br />
  1058. Remove a model (or an array of models) from the collection. Fires a
  1059. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  1060. to suppress.
  1061. </p>
  1062. <p id="Collection-get">
  1063. <b class="header">get</b><code>collection.get(id)</code>
  1064. <br />
  1065. Get a model from a collection, specified by <b>id</b>.
  1066. </p>
  1067. <pre>
  1068. var book = Library.get(110);
  1069. </pre>
  1070. <p id="Collection-getByCid">
  1071. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  1072. <br />
  1073. Get a model from a collection, specified by client id. The client id
  1074. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  1075. a model is created. Useful for models which have not yet been saved to
  1076. the server, and do not yet have true ids.
  1077. </p>
  1078. <p id="Collection-at">
  1079. <b class="header">at</b><code>collection.at(index)</code>
  1080. <br />
  1081. Get a model from a collection, specified by index. Useful if your collection
  1082. is sorted, and if your collection isn't sorted, <b>at</b> will still
  1083. retrieve models in insertion order.
  1084. </p>
  1085. <p id="Collection-length">
  1086. <b class="header">length</b><code>collection.length</code>
  1087. <br />
  1088. Like an array, a Collection maintains a <tt>length</tt> property, counting
  1089. the number of models it contains.
  1090. </p>
  1091. <p id="Collection-comparator">
  1092. <b class="header">comparator</b><code>collection.comparator</code>
  1093. <br />
  1094. By default there is no <b>comparator</b> function on a collection.
  1095. If you define a comparator, it will be used to maintain
  1096. the collection in sorted order. This means that as models are added,
  1097. they are inserted at the correct index in <tt>collection.models</tt>.
  1098. Comparator functions take a model and return a numeric or string value
  1099. by which the model should be ordered relative to others.
  1100. </p>
  1101. <p>
  1102. Note how even though all of the chapters in this example are added backwards,
  1103. they come out in the proper order:
  1104. </p>
  1105. <pre class="runnable">
  1106. var Chapter = Backbone.Model;
  1107. var chapters = new Backbone.Collection;
  1108. chapters.comparator = function(chapter) {
  1109. return chapter.get("page");
  1110. };
  1111. chapters.add(new Chapter({page: 9, title: "The End"}));
  1112. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1113. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1114. alert(chapters.pluck('title'));
  1115. </pre>
  1116. <p class="warning">
  1117. Brief aside: This comparator function is different than JavaScript's regular
  1118. "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
  1119. and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
  1120. </p>
  1121. <p class="warning">
  1122. Collections with comparator functions will not automatically re-sort if you
  1123. later change model attributes, so you may wish to call <tt>sort</tt> after
  1124. changing model attributes that would affect the order.
  1125. </p>
  1126. <p id="Collection-sort">
  1127. <b class="header">sort</b><code>collection.sort([options])</code>
  1128. <br />
  1129. Force a collection to re-sort itself. You don't need to call this under
  1130. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1131. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1132. triggers the collection's <tt>"reset"</tt> event, unless silenced by passing
  1133. <tt>{silent: true}</tt>
  1134. </p>
  1135. <p id="Collection-pluck">
  1136. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1137. <br />
  1138. Pluck an attribute from each model in the collection. Equivalent to calling
  1139. <tt>map</tt>, and returning a single attribute from the iterator.
  1140. </p>
  1141. <pre class="runnable">
  1142. var stooges = new Backbone.Collection([
  1143. new Backbone.Model({name: "Curly"}),
  1144. new Backbone.Model({name: "Larry"}),
  1145. new Backbone.Model({name: "Moe"})
  1146. ]);
  1147. var names = stooges.pluck("name");
  1148. alert(JSON.stringify(names));
  1149. </pre>
  1150. <p id="Collection-url">
  1151. <b class="header">url</b><code>collection.url or collection.url()</code>
  1152. <br />
  1153. Set the <b>url</b> property (or function) on a collection to reference
  1154. its location on the server. Models within the collection will use <b>url</b>
  1155. to construct URLs of their own.
  1156. </p>
  1157. <pre>
  1158. var Notes = Backbone.Collection.extend({
  1159. url: '/notes'
  1160. });
  1161. // Or, something more sophisticated:
  1162. var Notes = Backbone.Collection.extend({
  1163. url: function() {
  1164. return this.document.url() + '/notes';
  1165. }
  1166. });
  1167. </pre>
  1168. <p id="Collection-parse">
  1169. <b class="header">parse</b><code>collection.parse(response)</code>
  1170. <br />
  1171. <b>parse</b> is called by Backbone whenever a collection's models are
  1172. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1173. The function is passed the raw <tt>response</tt> object, and should return
  1174. the array of model attributes to be <a href="#Collection-add">added</a>
  1175. to the collection. The default implementation is a no-op, simply passing
  1176. through the JSON response. Override this if you need to work with a
  1177. preexisting API, or better namespace your responses.
  1178. </p>
  1179. <pre>
  1180. var Tweets = Backbone.Collection.extend({
  1181. // The Twitter Search API returns tweets under "results".
  1182. parse: function(response) {
  1183. return response.results;
  1184. }
  1185. });
  1186. </pre>
  1187. <p id="Collection-fetch">
  1188. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1189. <br />
  1190. Fetch the default set of models for this collection from the server,
  1191. resetting the collection when they arrive. The <b>options</b> hash takes
  1192. <tt>success</tt> and <tt>error</tt>
  1193. callbacks which will be passed <tt>(collec

Large files files are truncated, but you can click here to view the full file