PageRenderTime 65ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/index.html

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

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