PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/index.html

https://github.com/StevenBlack/backbone
HTML | 2161 lines | 1854 code | 307 blank | 0 comment | 0 complexity | 7b0456a645b388e3a5841b2a67765515 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-set">
  487. <b class="header">set</b><code>model.set(attributes, [options])</code>
  488. <br />
  489. Set a hash of attributes (one or many) on the model. If any of the attributes
  490. change the models state, a <tt>"change"</tt> event will be triggered, unless
  491. <tt>{silent: true}</tt> is passed as an option. Change events for specific
  492. attributes are also triggered, and you can bind to those as well, for example:
  493. <tt>change:title</tt>, and <tt>change:content</tt>.
  494. </p>
  495. <pre>
  496. note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
  497. </pre>
  498. <p>
  499. If the model has a <a href="#Model-validate">validate</a> method,
  500. it will be validated before the attributes are set, no changes will
  501. occur if the validation fails, and <b>set</b> will return <tt>false</tt>.
  502. You may also pass an <tt>error</tt>
  503. callback in the options, which will be invoked instead of triggering an
  504. <tt>"error"</tt> event, should validation fail.
  505. </p>
  506. <p id="Model-escape">
  507. <b class="header">escape</b><code>model.escape(attribute)</code>
  508. <br />
  509. Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version
  510. of a model's attribute. If you're interpolating data from the model into
  511. HTML, using <b>escape</b> to retrieve attributes will prevent
  512. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks.
  513. </p>
  514. <pre class="runnable">
  515. var hacker = new Backbone.Model({
  516. name: "&lt;script&gt;alert('xss')&lt;/script&gt;"
  517. });
  518. alert(hacker.escape('name'));
  519. </pre>
  520. <p id="Model-has">
  521. <b class="header">has</b><code>model.has(attribute)</code>
  522. <br />
  523. Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined
  524. value.
  525. </p>
  526. <pre>
  527. if (note.has("title")) {
  528. ...
  529. }
  530. </pre>
  531. <p id="Model-unset">
  532. <b class="header">unset</b><code>model.unset(attribute, [options])</code>
  533. <br />
  534. Remove an attribute by deleting it from the internal attributes hash.
  535. Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
  536. </p>
  537. <p id="Model-clear">
  538. <b class="header">clear</b><code>model.clear([options])</code>
  539. <br />
  540. Removes all attributes from the model. Fires a <tt>"change"</tt> event unless
  541. <tt>silent</tt> is passed as an option.
  542. </p>
  543. <p id="Model-id">
  544. <b class="header">id</b><code>model.id</code>
  545. <br />
  546. A special property of models, the <b>id</b> is an arbitrary string
  547. (integer id or UUID). If you set the <b>id</b> in the
  548. attributes hash, it will be copied onto the model as a direct property.
  549. Models can be retrieved by id from collections, and the id is used to generate
  550. model URLs by default.
  551. </p>
  552. <p id="Model-cid">
  553. <b class="header">cid</b><code>model.cid</code>
  554. <br />
  555. A special property of models, the <b>cid</b> or client id is a unique identifier
  556. automatically assigned to all models when they're first created. Client ids
  557. are handy when the model has not yet been saved to the server, and does not
  558. yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
  559. Client ids take the form: <tt>c1, c2, c3 ...</tt>
  560. </p>
  561. <p id="Model-attributes">
  562. <b class="header">attributes</b><code>model.attributes</code>
  563. <br />
  564. The <b>attributes</b> property is the internal hash containing the model's
  565. state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
  566. them directly. If you'd like to retrieve and munge a copy of the model's
  567. attributes, use <a href="#Model-toJSON">toJSON</a> instead.
  568. </p>
  569. <p id="Model-defaults">
  570. <b class="header">defaults</b><code>model.defaults or model.defaults()</code>
  571. <br />
  572. The <b>defaults</b> hash (or function) can be used to specify the default
  573. attributes for your model. When creating an instance of the model,
  574. any unspecified attributes will be set to their default value.
  575. </p>
  576. <pre class="runnable">
  577. var Meal = Backbone.Model.extend({
  578. defaults: {
  579. "appetizer": "caesar salad",
  580. "entree": "ravioli",
  581. "dessert": "cheesecake"
  582. }
  583. });
  584. alert("Dessert will be " + (new Meal).get('dessert'));
  585. </pre>
  586. <p id="Model-toJSON">
  587. <b class="header">toJSON</b><code>model.toJSON()</code>
  588. <br />
  589. Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
  590. This can be used for persistence, serialization, or for augmentation before
  591. being handed off to a view. The name of this method is a bit confusing, as
  592. it doesn't actually return a JSON string &mdash; but I'm afraid that it's
  593. the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
  594. </p>
  595. <pre class="runnable">
  596. var artist = new Backbone.Model({
  597. firstName: "Wassily",
  598. lastName: "Kandinsky"
  599. });
  600. artist.set({birthday: "December 16, 1866"});
  601. alert(JSON.stringify(artist));
  602. </pre>
  603. <p id="Model-fetch">
  604. <b class="header">fetch</b><code>model.fetch([options])</code>
  605. <br />
  606. Refreshes the model's state from the server. Useful if the model has never
  607. been populated with data, or if you'd like to ensure that you have the
  608. latest server state. A <tt>"change"</tt> event will be triggered if the
  609. server's state differs from the current attributes. Accepts
  610. <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
  611. are passed <tt>(model, response)</tt> as arguments.
  612. </p>
  613. <pre>
  614. // Poll every 10 seconds to keep the channel model up-to-date.
  615. setInterval(function() {
  616. channel.fetch();
  617. }, 10000);
  618. </pre>
  619. <p id="Model-save">
  620. <b class="header">save</b><code>model.save([attributes], [options])</code>
  621. <br />
  622. Save a model to your database (or alternative persistence layer),
  623. by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b>
  624. hash (as in <a href="#Model-set">set</a>) should contain the attributes
  625. you'd like to change -- keys that aren't mentioned won't be altered.
  626. If the model has a <a href="#Model-validate">validate</a>
  627. method, and validation fails, the model will not be saved. If the model
  628. <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
  629. (HTTP <tt>POST</tt>), if the model already
  630. exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>).
  631. </p>
  632. <p>
  633. In the following example, notice how because the model has never been
  634. saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
  635. </p>
  636. <pre class="runnable">
  637. Backbone.sync = function(method, model) {
  638. alert(method + ": " + JSON.stringify(model));
  639. };
  640. var book = new Backbone.Model({
  641. title: "The Rough Riders",
  642. author: "Theodore Roosevelt"
  643. });
  644. book.save();
  645. </pre>
  646. <p>
  647. <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the
  648. options hash, which are passed <tt>(model, response)</tt> as arguments.
  649. The <tt>error</tt> callback will also be invoked if the model has a
  650. <tt>validate</tt> method, and validation fails. If a server-side
  651. validation fails, return a non-<tt>200</tt> HTTP response code, along with
  652. an error response in text or JSON.
  653. </p>
  654. <pre>
  655. book.save({author: "F.D.R."}, {error: function(){ ... }});
  656. </pre>
  657. <p id="Model-destroy">
  658. <b class="header">destroy</b><code>model.destroy([options])</code>
  659. <br />
  660. Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
  661. request to <a href="#Sync">Backbone.sync</a>. Accepts
  662. <tt>success</tt> and <tt>error</tt> callbacks in the options hash.
  663. </p>
  664. <pre>
  665. book.destroy({success: function(model, response) {
  666. ...
  667. }});
  668. </pre>
  669. <p id="Model-validate">
  670. <b class="header">validate</b><code>model.validate(attributes)</code>
  671. <br />
  672. This method is left undefined, and you're encouraged to override it with
  673. your custom validation logic, if you have any that can be performed
  674. in JavaScript. <b>validate</b> is called before <tt>set</tt> and
  675. <tt>save</tt>, and is passed the attributes that are about to be updated.
  676. If the model and attributes are valid, don't return anything from <b>validate</b>;
  677. if the attributes are invalid, return an error of your choosing. It
  678. can be as simple as a string error message to be displayed, or a complete
  679. error object that describes the error programmatically. <tt>set</tt> and
  680. <tt>save</tt> will not continue if <b>validate</b> returns an error.
  681. Failed validations trigger an <tt>"error"</tt> event.
  682. </p>
  683. <pre class="runnable">
  684. var Chapter = Backbone.Model.extend({
  685. validate: function(attrs) {
  686. if (attrs.end < attrs.start) {
  687. return "can't end before it starts";
  688. }
  689. }
  690. });
  691. var one = new Chapter({
  692. title : "Chapter One: The Beginning"
  693. });
  694. one.bind("error", function(model, error) {
  695. alert(model.get("title") + " " + error);
  696. });
  697. one.set({
  698. start: 15,
  699. end: 10
  700. });
  701. </pre>
  702. <p>
  703. <tt>"error"</tt> events are useful for providing coarse-grained error
  704. messages at the model or collection level, but if you have a specific view
  705. that can better handle the error, you may override and suppress the event
  706. by passing an <tt>error</tt> callback directly:
  707. </p>
  708. <pre>
  709. account.set({access: "unlimited"}, {
  710. error: function(model, error) {
  711. alert(error);
  712. }
  713. });
  714. </pre>
  715. <p id="Model-url">
  716. <b class="header">url</b><code>model.url()</code>
  717. <br />
  718. Returns the relative URL where the model's resource would be located on
  719. the server. If your models are located somewhere else, override this method
  720. with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>,
  721. falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection.
  722. </p>
  723. <p>
  724. Delegates to <a href="#Collection-url">Collection#url</a> to generate the
  725. URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a>
  726. property, if all models of this class share a common root URL.
  727. A model with an id of <tt>101</tt>, stored in a
  728. <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>,
  729. would have this URL: <tt>"/documents/7/notes/101"</tt>
  730. </p>
  731. <p id="Model-urlRoot">
  732. <b class="header">urlRoot</b><code>model.urlRoot</code>
  733. <br />
  734. Specify a <tt>urlRoot</tt> if you're using a model outside of a collection,
  735. to enable the default <a href="#Model-url">url</a> function to generate
  736. URLs based on the model id. <tt>"/[urlRoot]/id"</tt>
  737. </p>
  738. <pre class="runnable">
  739. var Book = Backbone.Model.extend({urlRoot : '/books'});
  740. var solaris = new Book({id: "1083-lem-solaris"});
  741. alert(solaris.url());
  742. </pre>
  743. <p id="Model-parse">
  744. <b class="header">parse</b><code>model.parse(response)</code>
  745. <br />
  746. <b>parse</b> is called whenever a model's data is returned by the
  747. server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>.
  748. The function is passed the raw <tt>response</tt> object, and should return
  749. the attributes hash to be <a href="#Model-set">set</a> on the model. The
  750. default implementation is a no-op, simply passing through the JSON response.
  751. Override this if you need to work with a preexisting API, or better namespace
  752. your responses.
  753. </p>
  754. <p>
  755. If you're working with a Rails backend, you'll notice that Rails' default
  756. <tt>to_json</tt> implementation includes a model's attributes under a
  757. namespace. To disable this behavior for seamless Backbone integration, set:
  758. </p>
  759. <pre>
  760. ActiveRecord::Base.include_root_in_json = false
  761. </pre>
  762. <p id="Model-clone">
  763. <b class="header">clone</b><code>model.clone()</code>
  764. <br />
  765. Returns a new instance of the model with identical attributes.
  766. </p>
  767. <p id="Model-isNew">
  768. <b class="header">isNew</b><code>model.isNew()</code>
  769. <br />
  770. Has this model been saved to the server yet? If the model does not yet have
  771. an <tt>id</tt>, it is considered to be new.
  772. </p>
  773. <p id="Model-change">
  774. <b class="header">change</b><code>model.change()</code>
  775. <br />
  776. Manually trigger the <tt>"change"</tt> event.
  777. If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
  778. aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
  779. when you're all finished.
  780. </p>
  781. <p id="Model-hasChanged">
  782. <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
  783. <br />
  784. Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
  785. is passed, returns <tt>true</tt> if that specific attribute has changed.
  786. </p>
  787. <pre>
  788. book.bind("change", function() {
  789. if (book.hasChanged("title")) {
  790. ...
  791. }
  792. });
  793. </pre>
  794. <p id="Model-changedAttributes">
  795. <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
  796. <br />
  797. Retrieve a hash of only the model's attributes that have changed. Optionally,
  798. an external <b>attributes</b> hash can be passed in, returning
  799. the attributes in that hash which differ from the model. This can be used
  800. to figure out which portions of a view should be updated, or what calls
  801. need to be made to sync the changes to the server.
  802. </p>
  803. <p id="Model-previous">
  804. <b class="header">previous</b><code>model.previous(attribute)</code>
  805. <br />
  806. During a <tt>"change"</tt> event, this method can be used to get the
  807. previous value of a changed attribute.
  808. </p>
  809. <pre class="runnable">
  810. var bill = new Backbone.Model({
  811. name: "Bill Smith"
  812. });
  813. bill.bind("change:name", function(model, name) {
  814. alert("Changed name from " + bill.previous("name") + " to " + name);
  815. });
  816. bill.set({name : "Bill Jones"});
  817. </pre>
  818. <p id="Model-previousAttributes">
  819. <b class="header">previousAttributes</b><code>model.previousAttributes()</code>
  820. <br />
  821. Return a copy of the model's previous attributes. Useful for getting a
  822. diff between versions of a model, or getting back to a valid state after
  823. an error occurs.
  824. </p>
  825. <h2 id="Collection">Backbone.Collection</h2>
  826. <p>
  827. Collections are ordered sets of models. You can to bind <tt>"change"</tt> events
  828. to be notified when any model in the collection has been modified,
  829. listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt>
  830. the collection from the server, and use a full suite of
  831. <a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
  832. </p>
  833. <p>
  834. Any event that is triggered on a model in a collection will also be
  835. triggered on the collection directly, for convenience.
  836. This allows you to listen for changes to specific attributes in any
  837. model in a collection, for example:
  838. <tt>Documents.bind("change:selected", ...)</tt>
  839. </p>
  840. <p id="Collection-extend">
  841. <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
  842. <br />
  843. To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
  844. providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
  845. directly to the collection's constructor function.
  846. </p>
  847. <p id="Collection-model">
  848. <b class="header">model</b><code>collection.model</code>
  849. <br />
  850. Override this property to specify the model class that the collection
  851. contains. If defined, you can pass raw attributes objects (and arrays) to
  852. <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>,
  853. and <a href="#Collection-refresh">refresh</a>, and the attributes will be
  854. converted into a model of the proper type.
  855. </p>
  856. <pre>
  857. var Library = Backbone.Collection.extend({
  858. model: Book
  859. });
  860. </pre>
  861. <p id="Collection-constructor">
  862. <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
  863. <br />
  864. When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
  865. The collection's <a href="#Collection-comparator">comparator</a> function
  866. may be included as an option. If you define an <b>initialize</b> function, it will be
  867. invoked when the collection is created.
  868. </p>
  869. <pre>
  870. var tabs = new TabSet([tab1, tab2, tab3]);
  871. </pre>
  872. <p id="Collection-models">
  873. <b class="header">models</b><code>collection.models</code>
  874. <br />
  875. Raw access to the JavaScript array of models inside of the collection. Usually you'll
  876. want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
  877. to access model objects, but occasionally a direct reference to the array
  878. is desired.
  879. </p>
  880. <p id="Collection-toJSON">
  881. <b class="header">toJSON</b><code>collection.toJSON()</code>
  882. <br />
  883. Return an array containing the attributes hash of each model in the
  884. collection. This can be used to serialize and persist the
  885. collection as a whole. The name of this method is a bit confusing, because
  886. it conforms to
  887. <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>.
  888. </p>
  889. <pre class="runnable">
  890. var collection = new Backbone.Collection([
  891. {name: "Tim", age: 5},
  892. {name: "Ida", age: 26},
  893. {name: "Rob", age: 55}
  894. ]);
  895. alert(JSON.stringify(collection));
  896. </pre>
  897. <p id="Collection-Underscore-Methods">
  898. <b class="header">Underscore Methods (25)</b>
  899. <br />
  900. Backbone proxies to <b>Underscore.js</b> to provide 25 iteration functions
  901. on <b>Backbone.Collection</b>. They aren't all documented here, but
  902. you can take a look at the Underscore documentation for the full details&hellip;
  903. </p>
  904. <ul>
  905. <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
  906. <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
  907. <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
  908. <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
  909. <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
  910. <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
  911. <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
  912. <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
  913. <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
  914. <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
  915. <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
  916. <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
  917. <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
  918. <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
  919. <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
  920. <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
  921. <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
  922. <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
  923. <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
  924. <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
  925. <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
  926. <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
  927. <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
  928. <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
  929. <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li>
  930. </ul>
  931. <pre>
  932. Books.each(function(book) {
  933. book.publish();
  934. });
  935. var titles = Books.map(function(book) {
  936. return book.get("title");
  937. });
  938. var publishedBooks = Books.filter(function(book) {
  939. return book.get("published") === true;
  940. });
  941. var alphabetical = Books.sortBy(function(book) {
  942. return book.author.get("name").toLowerCase();
  943. });
  944. </pre>
  945. <p id="Collection-add">
  946. <b class="header">add</b><code>collection.add(models, [options])</code>
  947. <br />
  948. Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
  949. event, which you can pass <tt>{silent: true}</tt> to suppress. If a
  950. <a href="#Collection-model">model</a> property is defined, you may also pass
  951. raw attributes objects.
  952. </p>
  953. <pre class="runnable">
  954. var ships = new Backbone.Collection;
  955. ships.bind("add", function(ship) {
  956. alert("Ahoy " + ship.get("name") + "!");
  957. });
  958. ships.add([
  959. {name: "Flying Dutchman"},
  960. {name: "Black Pearl"}
  961. ]);
  962. </pre>
  963. <p id="Collection-remove">
  964. <b class="header">remove</b><code>collection.remove(models, [options])</code>
  965. <br />
  966. Remove a model (or an array of models) from the collection. Fires a
  967. <tt>"remove"</tt> event, which you can use <tt>silent</tt>
  968. to suppress.
  969. </p>
  970. <p id="Collection-get">
  971. <b class="header">get</b><code>collection.get(id)</code>
  972. <br />
  973. Get a model from a collection, specified by <b>id</b>.
  974. </p>
  975. <pre>
  976. var book = Library.get(110);
  977. </pre>
  978. <p id="Collection-getByCid">
  979. <b class="header">getByCid</b><code>collection.getByCid(cid)</code>
  980. <br />
  981. Get a model from a collection, specified by client id. The client id
  982. is the <tt>.cid</tt> property of the model, automatically assigned whenever
  983. a model is created. Useful for models which have not yet been saved to
  984. the server, and do not yet have true ids.
  985. </p>
  986. <p id="Collection-at">
  987. <b class="header">at</b><code>collection.at(index)</code>
  988. <br />
  989. Get a model from a collection, specified by index. Useful if your collection
  990. is sorted, and if your collection isn't sorted, <b>at</b> will still
  991. retrieve models in insertion order.
  992. </p>
  993. <p id="Collection-length">
  994. <b class="header">length</b><code>collection.length</code>
  995. <br />
  996. Like an array, a Collection maintains a <tt>length</tt> property, counting
  997. the number of models it contains.
  998. </p>
  999. <p id="Collection-comparator">
  1000. <b class="header">comparator</b><code>collection.comparator</code>
  1001. <br />
  1002. By default there is no <b>comparator</b> function on a collection.
  1003. If you define a comparator, it will be used to maintain
  1004. the collection in sorted order. This means that as models are added,
  1005. they are inserted at the correct index in <tt>collection.models</tt>.
  1006. Comparator functions take a model and return a numeric or string value
  1007. by which the model should be ordered relative to others.
  1008. </p>
  1009. <p>
  1010. Note how even though all of the chapters in this example are added backwards,
  1011. they come out in the proper order:
  1012. </p>
  1013. <pre class="runnable">
  1014. var Chapter = Backbone.Model;
  1015. var chapters = new Backbone.Collection;
  1016. chapters.comparator = function(chapter) {
  1017. return chapter.get("page");
  1018. };
  1019. chapters.add(new Chapter({page: 9, title: "The End"}));
  1020. chapters.add(new Chapter({page: 5, title: "The Middle"}));
  1021. chapters.add(new Chapter({page: 1, title: "The Beginning"}));
  1022. alert(chapters.pluck('title'));
  1023. </pre>
  1024. <p class="warning">
  1025. Brief aside: This comparator function is different than JavaScript's regular
  1026. "sort", which must return <tt>0</tt>, <tt>1</tt>, or <tt>-1</tt>,
  1027. and is more similar to a <tt>sortBy</tt> &mdash; a much nicer API.
  1028. </p>
  1029. <p id="Collection-sort">
  1030. <b class="header">sort</b><code>collection.sort([options])</code>
  1031. <br />
  1032. Force a collection to re-sort itself. You don't need to call this under
  1033. normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
  1034. will maintain itself in proper sort order at all times. Calling <b>sort</b>
  1035. triggers the collection's <tt>"refresh"</tt> event, unless silenced by passing
  1036. <tt>{silent: true}</tt>
  1037. </p>
  1038. <p id="Collection-pluck">
  1039. <b class="header">pluck</b><code>collection.pluck(attribute)</code>
  1040. <br />
  1041. Pluck an attribute from each model in the collection. Equivalent to calling
  1042. <tt>map</tt>, and returning a single attribute from the iterator.
  1043. </p>
  1044. <pre class="runnable">
  1045. var stooges = new Backbone.Collection([
  1046. new Backbone.Model({name: "Curly"}),
  1047. new Backbone.Model({name: "Larry"}),
  1048. new Backbone.Model({name: "Moe"})
  1049. ]);
  1050. var names = stooges.pluck("name");
  1051. alert(JSON.stringify(names));
  1052. </pre>
  1053. <p id="Collection-url">
  1054. <b class="header">url</b><code>collection.url or collection.url()</code>
  1055. <br />
  1056. Set the <b>url</b> property (or function) on a collection to reference
  1057. its location on the server. Models within the collection will use <b>url</b>
  1058. to construct URLs of their own.
  1059. </p>
  1060. <pre>
  1061. var Notes = Backbone.Collection.extend({
  1062. url: '/notes'
  1063. });
  1064. // Or, something more sophisticated:
  1065. var Notes = Backbone.Collection.extend({
  1066. url: function() {
  1067. return this.document.url() + '/notes';
  1068. }
  1069. });
  1070. </pre>
  1071. <p id="Collection-parse">
  1072. <b class="header">parse</b><code>collection.parse(response)</code>
  1073. <br />
  1074. <b>parse</b> is called by Backbone whenever a collection's models are
  1075. returned by the server, in <a href="#Collection-fetch">fetch</a>.
  1076. The function is passed the raw <tt>response</tt> object, and should return
  1077. the array of model attributes to be <a href="#Collection-add">added</a>
  1078. to the collection. The default implementation is a no-op, simply passing
  1079. through the JSON response. Override this if you need to work with a
  1080. preexisting API, or better namespace your responses.
  1081. </p>
  1082. <pre>
  1083. var Tweets = Backbone.Collection.extend({
  1084. // The Twitter Search API returns tweets under "results".
  1085. parse: function(response) {
  1086. return response.results;
  1087. }
  1088. });
  1089. </pre>
  1090. <p id="Collection-fetch">
  1091. <b class="header">fetch</b><code>collection.fetch([options])</code>
  1092. <br />
  1093. Fetch the default set of models for this collection from the server,
  1094. refreshing the collection when they arrive. The <b>options</b> hash takes
  1095. <tt>success</tt> and <tt>error</tt>
  1096. callbacks which will be passed <tt>(collection, response)</tt> as arguments.
  1097. When the model data returns from the server, the collection will
  1098. <a href="#Collection-refresh">refresh</a>.
  1099. Delegates to <a href="#Sync">Backbone.sync</a>
  1100. under the covers, for custom persistence strategies.
  1101. The server handler for <b>fetch</b> requests should return a JSON array of
  1102. models.
  1103. </p>
  1104. <pre class="runnable">
  1105. Backbone.sync = function(method, model) {
  1106. alert(method + ": " + model.url);
  1107. };
  1108. var Accounts = new Backbone.Collection;
  1109. Accounts.url = '/accounts';
  1110. Accounts.fetch();
  1111. </pre>
  1112. <p>
  1113. If you'd like to add the incoming models to the current collection, instead
  1114. of replacing the collection's contents, pass <tt>{add: true}</tt> as an
  1115. option to <b>fetch</b>.
  1116. </p>
  1117. <p>
  1118. Note that <b>fetch</b> should not be used to populate collections on
  1119. page load &mdash; all models needed at load time should already be
  1120. <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is
  1121. intended for lazily-loading models for interfaces that are not needed
  1122. immediately: for example, documents with collections of notes that may be
  1123. toggled open and closed.
  1124. </p>
  1125. <p id="Collection-refresh">
  1126. <b class="header">refresh</b><code>collection.refresh(models, [options])</code>
  1127. <br />
  1128. Adding and removing models one at a time is all well and good, but sometimes
  1129. you have so many models to change that you'd rather just update the collection
  1130. in bulk. Use <b>refresh</b> to replace a collection with a new list
  1131. of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
  1132. at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
  1133. </p>
  1134. <p>
  1135. Here's an example using <b>refresh</b> to bootstrap a collection during initial page load,
  1136. in a Rails application.
  1137. </p>
  1138. <pre>
  1139. &lt;script&gt;
  1140. Accounts.refresh(&lt;%= @accounts.to_json %&gt;);
  1141. &lt;/script&gt;
  1142. </pre>
  1143. <p id="Collection-create">
  1144. <b class="header">create</b><code>collection.create(attributes, [options])</code>
  1145. <br />
  1146. Convenience to create a new instance of a model within a collection.
  1147. Equivalent to instantiating a model with a hash of attributes,
  1148. saving the model to the server, and adding the model to the set after being
  1149. successfully created. Returns
  1150. the model, or <tt>false</tt> if a validation error prevented the
  1151. model from being created. In order for this to work, your should set the
  1152. <a href="#Collection-model">model</a> property of the collection.
  1153. </p>
  1154. <pre>
  1155. var Library = Backbone.Collection.extend({
  1156. model: Book
  1157. });
  1158. var NYPL = new Library;
  1159. var othello = NYPL.create({
  1160. title: "Othello",
  1161. author: "William Shakespeare"
  1162. });
  1163. </pre>
  1164. <h2 id="Controller">Backbone.Controller</h2>
  1165. <p>
  1166. Web applications often choose to change their URL fragment (<tt>#fragment</tt>)
  1167. in order to provide shareable, bookmarkable URLs for an Ajax-heavy application.
  1168. <b>Backbone.Controller</b> provides methods for routing client-side URL
  1169. fragments, and connecting them to actions and events.
  1170. </p>
  1171. <p class="warning">
  1172. Backbone controllers do not yet make use of HTML5 <b>pushState</b> and
  1173. <b>replaceState</b>. Currently, <b>pushState</b> and <b>replaceState</b>
  1174. need special handling on the server-side, cause you to mint duplicate URLs,
  1175. and have an incomplete API. We may start supporting them in the future
  1176. when these issues have been resolved.
  1177. </p>
  1178. <p>
  1179. During page load, after your application has finished creating all of its controllers,
  1180. be sure to call <tt>Backbone.history.start()</tt> to route the initial URL.
  1181. </p>
  1182. <p id="Controller-extend">
  1183. <b class="header">extend</b><code>Backbone.Controller.extend(properties, [classProperties])</code>
  1184. <br />
  1185. Get started by creating a custom controller class. You'll
  1186. want to define actions that are triggered when certain URL fragments are
  1187. matched, and provide a <a href="#Controller-routes">routes</a> hash
  1188. that pairs routes to actions.
  1189. </p>
  1190. <pre>
  1191. var Workspace = Backbone.Controller.extend({
  1192. routes: {
  1193. "help": "help", // #help
  1194. "search/:query": "search", // #search/kiwis
  1195. "search/:query/p:page": "search" // #search/kiwis/p7
  1196. },
  1197. help: function() {
  1198. ...
  1199. },
  1200. search: function(query, page) {
  1201. ...
  1202. }
  1203. });
  1204. </pre>
  1205. <p id="Controller-routes">
  1206. <b class="header">routes</b><code>controller.routes</code>
  1207. <br />
  1208. The routes hash maps URLs with parameters to functions on your controller,
  1209. similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>.
  1210. Routes can contain parameter parts, <tt>:param</tt>, which match a single URL
  1211. component b

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