PageRenderTime 67ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/index.html

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