PageRenderTime 51ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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

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