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

/index.html

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

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