PageRenderTime 73ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/index.html

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

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