PageRenderTime 92ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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

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