PageRenderTime 63ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

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

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