/node_modules/ender/test/node_modules/backbone/index.html
HTML | 1734 lines | 1514 code | 220 blank | 0 comment | 0 complexity | 91179267c4839a9621bcf74f1406e6a1 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 <link rel="icon" href="docs/images/favicon.ico" /> 7 <title>Backbone.js</title> 8 <style> 9 body { 10 font-size: 14px; 11 line-height: 22px; 12 font-family: Helvetica Neue, Helvetica, Arial; 13 background: #f4f4f4 url(docs/images/background.png); 14 } 15 .interface { 16 font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important; 17 } 18 div#sidebar { 19 background: #fff; 20 position: fixed; 21 top: 0; left: 0; bottom: 0; 22 width: 200px; 23 overflow-y: auto; 24 overflow-x: hidden; 25 padding: 15px 0 30px 30px; 26 border-right: 1px solid #bbb; 27 box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc; 28 } 29 a.toc_title, a.toc_title:visited { 30 display: block; 31 color: black; 32 font-weight: bold; 33 margin-top: 15px; 34 } 35 a.toc_title:hover { 36 text-decoration: underline; 37 } 38 #sidebar .version { 39 font-size: 10px; 40 font-weight: normal; 41 } 42 ul.toc_section { 43 font-size: 11px; 44 line-height: 14px; 45 margin: 5px 0 0 0; 46 padding-left: 0px; 47 list-style-type: none; 48 font-family: Lucida Grande; 49 } 50 .toc_section li { 51 cursor: pointer; 52 margin: 0 0 3px 0; 53 } 54 .toc_section li a { 55 text-decoration: none; 56 color: black; 57 } 58 .toc_section li a:hover { 59 text-decoration: underline; 60 } 61 div.container { 62 position: relative; 63 width: 550px; 64 margin: 40px 0 50px 260px; 65 } 66 div.run { 67 position: absolute; 68 right: 15px; 69 width: 26px; height: 18px; 70 background: url('docs/images/arrows.png') no-repeat -26px 0; 71 } 72 div.run:active { 73 background-position: -51px 0; 74 } 75 p, div.container ul { 76 margin: 25px 0; 77 width: 550px; 78 } 79 p.warning { 80 font-size: 12px; 81 line-height: 18px; 82 font-style: italic; 83 } 84 div.container ul { 85 list-style: circle; 86 padding-left: 15px; 87 font-size: 13px; 88 line-height: 18px; 89 } 90 div.container ul li { 91 margin-bottom: 10px; 92 } 93 div.container ul.small { 94 font-size: 12px; 95 } 96 a, a:visited { 97 color: #444; 98 } 99 a:active, a:hover { 100 color: #000; 101 } 102 a.punch { 103 display: inline-block; 104 background: #4162a8; 105 border-top: 1px solid #38538c; 106 border-right: 1px solid #1f2d4d; 107 border-bottom: 1px solid #151e33; 108 border-left: 1px solid #1f2d4d; 109 -webkit-border-radius: 4px; 110 -moz-border-radius: 4px; 111 -ms-border-radius: 4px; 112 -o-border-radius: 4px; 113 border-radius: 4px; 114 -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 115 -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 116 -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 117 -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 118 box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 119 color: #fff; 120 font: bold 14px "helvetica neue", helvetica, arial, sans-serif; 121 line-height: 1; 122 margin-bottom: 15px; 123 padding: 8px 0 10px 0; 124 text-align: center; 125 text-shadow: 0px -1px 1px #1e2d4d; 126 text-decoration: none; 127 width: 225px; 128 -webkit-background-clip: padding-box; } 129 a.punch:hover { 130 -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 131 -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 132 -ms-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 133 -o-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 134 box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111; 135 cursor: pointer; } 136 a.punch:active { 137 -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; 138 -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; 139 -ms-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; 140 -o-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; 141 box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; 142 margin-top: 5px; margin-bottom: 10px } 143 a img { 144 border: 0; 145 } 146 h1, h2, h3, h4, h5, h6 { 147 padding-top: 20px; 148 } 149 h2 { 150 font-size: 22px; 151 } 152 b.header { 153 font-size: 18px; 154 line-height: 35px; 155 } 156 span.alias { 157 font-size: 14px; 158 font-style: italic; 159 margin-left: 20px; 160 } 161 table { 162 margin: 15px 0 0; padding: 0; 163 } 164 tr, td { 165 margin: 0; padding: 0; 166 } 167 td { 168 padding: 0px 15px 5px 0; 169 } 170 code, pre, tt { 171 font-family: Monaco, Consolas, "Lucida Console", monospace; 172 font-size: 12px; 173 line-height: 18px; 174 font-style: normal; 175 } 176 tt { 177 padding: 0px 3px; 178 background: #fff; 179 border: 1px solid #ddd; 180 zoom: 1; 181 } 182 code { 183 margin-left: 20px; 184 } 185 pre { 186 font-size: 12px; 187 padding: 2px 0 2px 15px; 188 border: 4px solid #bbb; border-top: 0; border-bottom: 0; 189 margin: 0px 0 25px; 190 } 191 img.example_image { 192 margin: 0px auto; 193 } 194 </style> 195</head> 196<body> 197 198 <div id="sidebar" class="interface"> 199 200 <a class="toc_title" href="#"> 201 Backbone.js <span class="version">(0.9.1)</span> 202 </a> 203 204 <a class="toc_title" href="#introduction"> 205 Introduction 206 </a> 207 208 <a class="toc_title" href="#upgrading"> 209 Upgrading 210 </a> 211 212 <a class="toc_title" href="#Events"> 213 Events 214 </a> 215 <ul class="toc_section"> 216 <li> <a href="#Events-on">on</a></li> 217 <li> <a href="#Events-off">off</a></li> 218 <li> <a href="#Events-trigger">trigger</a></li> 219 </ul> 220 221 <a class="toc_title" href="#Model"> 222 Model 223 </a> 224 <ul class="toc_section"> 225 <li> <a href="#Model-extend">extend</a></li> 226 <li> <a href="#Model-constructor">constructor / initialize</a></li> 227 <li> <a href="#Model-get">get</a></li> 228 <li> <a href="#Model-set">set</a></li> 229 <li> <a href="#Model-escape">escape</a></li> 230 <li> <a href="#Model-has">has</a></li> 231 <li> <a href="#Model-unset">unset</a></li> 232 <li> <a href="#Model-clear">clear</a></li> 233 <li> <a href="#Model-id">id</a></li> 234 <li> <a href="#Model-idAttribute">idAttribute</a></li> 235 <li> <a href="#Model-cid">cid</a></li> 236 <li> <a href="#Model-attributes">attributes</a></li> 237 <li> <a href="#Model-defaults">defaults</a></li> 238 <li>- <a href="#Model-toJSON">toJSON</a></li> 239 <li> <a href="#Model-fetch">fetch</a></li> 240 <li> <a href="#Model-save">save</a></li> 241 <li> <a href="#Model-destroy">destroy</a></li> 242 <li> <a href="#Model-validate">validate</a></li> 243 <li> <a href="#Model-isValid">isValid</a></li> 244 <li> <a href="#Model-url">url</a></li> 245 <li> <a href="#Model-urlRoot">urlRoot</a></li> 246 <li> <a href="#Model-parse">parse</a></li> 247 <li> <a href="#Model-clone">clone</a></li> 248 <li> <a href="#Model-isNew">isNew</a></li> 249 <li> <a href="#Model-change">change</a></li> 250 <li> <a href="#Model-hasChanged">hasChanged</a></li> 251 <li> <a href="#Model-changedAttributes">changedAttributes</a></li> 252 <li> <a href="#Model-previous">previous</a></li> 253 <li> <a href="#Model-previousAttributes">previousAttributes</a></li> 254 </ul> 255 256 <a class="toc_title" href="#Collection"> 257 Collection 258 </a> 259 <ul class="toc_section"> 260 <li> <a href="#Collection-extend">extend</a></li> 261 <li> <a href="#Collection-model">model</a></li> 262 <li> <a href="#Collection-constructor">constructor / initialize</a></li> 263 <li> <a href="#Collection-models">models</a></li> 264 <li> <a href="#Collection-toJSON">toJSON</a></li> 265 <li> <a href="#Collection-Underscore-Methods"><b>Underscore Methods (28)</b></a></li> 266 <li> <a href="#Collection-add">add</a></li> 267 <li> <a href="#Collection-remove">remove</a></li> 268 <li> <a href="#Collection-get">get</a></li> 269 <li> <a href="#Collection-getByCid">getByCid</a></li> 270 <li> <a href="#Collection-at">at</a></li> 271 <li> <a href="#Collection-length">length</a></li> 272 <li> <a href="#Collection-comparator">comparator</a></li> 273 <li> <a href="#Collection-sort">sort</a></li> 274 <li> <a href="#Collection-pluck">pluck</a></li> 275 <li> <a href="#Collection-url">url</a></li> 276 <li> <a href="#Collection-parse">parse</a></li> 277 <li> <a href="#Collection-fetch">fetch</a></li> 278 <li> <a href="#Collection-reset">reset</a></li> 279 <li> <a href="#Collection-create">create</a></li> 280 </ul> 281 282 <a class="toc_title" href="#Router"> 283 Router 284 </a> 285 <ul class="toc_section"> 286 <li> <a href="#Router-extend">extend</a></li> 287 <li> <a href="#Router-routes">routes</a></li> 288 <li> <a href="#Router-constructor">constructor / initialize</a></li> 289 <li> <a href="#Router-route">route</a></li> 290 <li> <a href="#Router-navigate">navigate</a></li> 291 </ul> 292 293 <a class="toc_title" href="#History"> 294 History 295 </a> 296 <ul class="toc_section"> 297 <li> <a href="#History-start">start</a></li> 298 </ul> 299 300 <a class="toc_title" href="#Sync"> 301 Sync 302 </a> 303 <ul class="toc_section"> 304 <li> <a href="#Sync">Backbone.sync</a></li> 305 <li> <a href="#Sync-emulateHTTP">Backbone.emulateHTTP</a></li> 306 <li> <a href="#Sync-emulateJSON">Backbone.emulateJSON</a></li> 307 </ul> 308 309 <a class="toc_title" href="#View"> 310 View 311 </a> 312 <ul class="toc_section"> 313 <li> <a href="#View-extend">extend</a></li> 314 <li> <a href="#View-constructor">constructor / initialize</a></li> 315 <li> <a href="#View-el">el</a></li> 316 <li> <a href="#View-$el">$el</a></li> 317 <li> <a href="#View-setElement">setElement</a></li> 318 <li> <a href="#View-attributes">attributes</a></li> 319 <li> <a href="#View-dollar">$ (jQuery or Zepto)</a></li> 320 <li> <a href="#View-render">render</a></li> 321 <li> <a href="#View-remove">remove</a></li> 322 <li> <a href="#View-make">make</a></li> 323 <li> <a href="#View-delegateEvents">delegateEvents</a></li> 324 <li> <a href="#View-undelegateEvents">undelegateEvents</a></li> 325 </ul> 326 327 <a class="toc_title" href="#Utility"> 328 Utility 329 </a> 330 <ul class="toc_section"> 331 <li> <a href="#Utility-noConflict">noConflict</a></li> 332 <li> <a href="#Utility-setDomLibrary">setDomLibrary</a></li> 333 </ul> 334 335 <a class="toc_title" href="#examples"> 336 Examples 337 </a> 338 <ul class="toc_section"> 339 <li> <a href="#examples-todos">Todos</a></li> 340 <li> <a href="#examples-documentcloud">DocumentCloud</a></li> 341 <li> <a href="#examples-linkedin">LinkedIn Mobile</a></li> 342 <li> <a href="#examples-flow">Flow</a></li> 343 <li> <a href="#examples-audiovroom">AudioVroom</a></li> 344 <li> <a href="#examples-foursquare">Foursquare</a></li> 345 <li> <a href="#examples-do">Do</a></li> 346 <li> <a href="#examples-posterous">Posterous Spaces</a></li> 347 <li> <a href="#examples-groupon">Groupon Now!</a></li> 348 <li> <a href="#examples-basecamp">Basecamp Mobile</a></li> 349 <li> <a href="#examples-slavery-footprint">Slavery Footprint</a></li> 350 <li>- <a href="#examples-stripe">Stripe</a></li> 351 <li> <a href="#examples-diaspora">Diaspora</a></li> 352 <li> <a href="#examples-trajectory">Trajectory</a></li> 353 <li> <a href="#examples-soundcloud">SoundCloud Mobile</a></li> 354 <li> <a href="#examples-pandora">Pandora</a></li> 355 <li>- <a href="#examples-code-school">Code School</a></li> 356 <li> <a href="#examples-cloudapp">CloudApp</a></li> 357 <li> <a href="#examples-seatgeek">SeatGeek</a></li> 358 <li> <a href="#examples-grove">Grove.io</a></li> 359 <li> <a href="#examples-kicksend">Kicksend</a></li> 360 <li> <a href="#examples-shortmail">Shortmail</a></li> 361 <li> <a href="#examples-battlefield">Battlefield Play4Free</a></li> 362 <li> <a href="#examples-salon">Salon.io</a></li> 363 <li> <a href="#examples-quoteroller">Quote Roller</a></li> 364 <li> <a href="#examples-tilemill">TileMill</a></li> 365 <li>- <a href="#examples-blossom">Blossom</a></li> 366 <li>- <a href="#examples-animoto">Animoto</a></li> 367 <li>- <a href="#examples-decide">Decide</a></li> 368 <li>- <a href="#examples-trello">Trello</a></li> 369 <li>- <a href="#examples-bittorrent">BitTorrent</a></li> 370 <li>- <a href="#examples-ducksboard">Ducksboard</a></li> 371 <li>- <a href="#examples-quietwrite">QuietWrite</a></li> 372 <li>- <a href="#examples-tzigla">Tzigla</a></li> 373 </ul> 374 375 <a class="toc_title" href="#faq"> 376 F.A.Q. 377 </a> 378 <ul class="toc_section"> 379 <li> <a href="#FAQ-events">Catalog of Events</a></li> 380 <li> <a href="#FAQ-tim-toady">More Than One Way To Do It</a></li> 381 <li> <a href="#FAQ-nested">Nested Models & Collections</a></li> 382 <li> <a href="#FAQ-bootstrap">Loading Bootstrapped Models</a></li> 383 <li> <a href="#FAQ-extending">Extending Backbone</a></li> 384 <li> <a href="#FAQ-mvc">Traditional MVC</a></li> 385 <li> <a href="#FAQ-this">Binding "this"</a></li> 386 <li> <a href="#FAQ-rails">Working with Rails</a></li> 387 </ul> 388 389 <a class="toc_title" href="#changelog"> 390 Change Log 391 </a> 392 393 </div> 394 395 <div class="container"> 396 397 <p> 398 <img style="width: 451px; height: 80px;" src="docs/images/backbone.png" alt="Backbone.js" /> 399 </p> 400 401 <p> 402 Backbone.js gives structure to your serious JavaScript web applications 403 by supplying <b>models</b> with key-value binding and custom events, 404 <b>collections</b> with a rich API of enumerable functions, 405 <b>views</b> with declarative event handling, and connects it all to your 406 existing API over a RESTful JSON interface. 407 </p> 408 409 <p> 410 The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>, 411 and the <a href="docs/backbone.html">annotated source code</a> is available, 412 as well as an online <a href="test/test.html">test suite</a>, 413 an <a href="examples/todos/index.html">example application</a>, 414 a <a href="https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites">list of tutorials</a> 415 and a <a href="#examples">long list of real-world projects</a> that use Backbone. 416 </p> 417 418 <p> 419 You can report bugs and discuss features on the 420 <a href="http://github.com/documentcloud/backbone/issues">GitHub issues page</a>, 421 on Freenode IRC in the <tt>#documentcloud</tt> channel, post questions to the 422 <a href="https://groups.google.com/forum/#!forum/backbonejs">Google Group</a>, 423 add pages to the a <a href="https://github.com/documentcloud/backbone/wiki">wiki</a> 424 or send tweets to <a href="http://twitter.com/documentcloud">@documentcloud</a>. 425 </p> 426 427 <p> 428 <i> 429 Backbone is an open-source component of 430 <a href="http://documentcloud.org/">DocumentCloud</a>. 431 </i> 432 </p> 433 434 <h2 id="downloads"> 435 Downloads & Dependencies 436 <span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span> 437 </h2> 438 439 <table> 440 <tr> 441 <td><a class="punch" href="backbone.js">Development Version (0.9.1)</a></td> 442 <td><i>47kb, Full source, lots of comments</i></td> 443 </tr> 444 <tr> 445 <td><a class="punch" href="backbone-min.js">Production Version (0.9.1)</a></td> 446 <td><i>5.3kb, Packed and gzipped</i></td> 447 </tr> 448 </table> 449 450 <p> 451 Backbone's only hard dependency is 452 <a href="http://documentcloud.github.com/underscore/">Underscore.js</a> <small>( > 1.3.1)</small>. 453 For RESTful persistence, history support via <a href="#Router">Backbone.Router</a> 454 and DOM manipulation with <a href="#View">Backbone.View</a>, include 455 <a href="https://github.com/douglascrockford/JSON-js">json2.js</a>, and either 456 <a href="http://jquery.com">jQuery</a> <small>( > 1.4.2)</small> or 457 <a href="http://zeptojs.com/">Zepto</a>. 458 </p> 459 460 <h2 id="introduction">Introduction</h2> 461 462 <p> 463 When working on a web application that involves a lot of JavaScript, one 464 of the first things you learn is to stop tying your data to the DOM. It's all 465 too easy to create JavaScript applications that end up as tangled piles of 466 jQuery selectors and callbacks, all trying frantically to keep data in 467 sync between the HTML UI, your JavaScript logic, and the database on your 468 server. For rich client-side applications, a more structured approach 469 is often helpful. 470 </p> 471 472 <p> 473 With Backbone, you represent your data as 474 <a href="#Model">Models</a>, which can be created, validated, destroyed, 475 and saved to the server. Whenever a UI action causes an attribute of 476 a model to change, the model triggers a <i>"change"</i> event; all 477 the <a href="#View">Views</a> that display the model's state can be notified of the 478 change, so that they are able to respond accordingly, re-rendering themselves with 479 the new information. In a finished Backbone app, you don't have to write the glue 480 code that looks into the DOM to find an element with a specific <i>id</i>, 481 and update the HTML manually 482 — when the model changes, the views simply update themselves. 483 </p> 484 485 <p> 486 Many of the examples that follow are runnable. Click the <i>play</i> button 487 to execute them. 488 </p> 489 490 <h2 id="upgrading">Upgrading to 0.9</h2> 491 492 <p> 493 Backbone's <b>0.9</b> series should be considered as a release candidate 494 for an upcoming <b>1.0</b>. Some APIs have changed, and while there is a 495 <a href="#changelog">change log</a> available, and many new features to 496 take advantage of, there are a few specific changes where you'll need 497 to take care: 498 </p> 499 500 <ul> 501 <li> 502 If you've ever manually set <tt>this.el</tt> in a Backbone View to be a 503 particular DOM element, you'll want to use 504 <a href="#View-setElement">setElement</a> instead. 505 </li> 506 <li> 507 Creating and destroying models is now optimistic. Pass <tt>{wait: true}</tt> 508 if you need the previous behavior of waiting for the server to acknowledge 509 success. You can now also pass <tt>{wait: true}</tt> to <a href="#Model-save">save</a> calls. 510 </li> 511 <li> 512 If you have been writing a fair amount of <tt>$(view.el)</tt>, there's now 513 a cached reference for that jQuery object: <a href="#View-$el">$el</a>. 514 </li> 515 <li> 516 If you're upgrading, make sure you also upgrade your version of Underscore.js 517 to the latest — 1.3.1 or greater. 518 </li> 519 </ul> 520 521 <h2 id="Events">Backbone.Events</h2> 522 523 <p> 524 <b>Events</b> is a module that can be mixed in to any object, giving the 525 object the ability to bind and trigger custom named events. Events do not 526 have to be declared before they are bound, and may take passed arguments. 527 For example: 528 </p> 529 530<pre class="runnable"> 531var object = {}; 532 533_.extend(object, Backbone.Events); 534 535object.on("alert", function(msg) { 536 alert("Triggered " + msg); 537}); 538 539object.trigger("alert", "an event"); 540</pre> 541 542 <p> 543 For example, to make a handy event dispatcher that can coordinate events 544 among different areas of your application: <tt>var dispatcher = _.clone(Backbone.Events)</tt> 545 </p> 546 547 <p id="Events-on"> 548 <b class="header">on</b><code>object.on(event, callback, [context])</code><span class="alias">Alias: bind</span> 549 <br /> 550 Bind a <b>callback</b> function to an object. The callback will be invoked 551 whenever the <b>event</b> is fired. 552 If you have a large number of different events on a page, the convention is to use colons to 553 namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>. 554 The event string may also be a space-delimited list of several events... 555 </p> 556 557<pre> 558book.on("change:title change:author", ...); 559</pre> 560 561 <p> 562 To supply a <b>context</b> value for <tt>this</tt> when the callback is invoked, 563 pass the optional third argument: <tt>model.on('change', this.render, this)</tt> 564 </p> 565 566 <p> 567 Callbacks bound to the special 568 <tt>"all"</tt> event will be triggered when any event occurs, and are passed 569 the name of the event as the first argument. For example, to proxy all events 570 from one object to another: 571 </p> 572 573<pre> 574proxy.on("all", function(eventName) { 575 object.trigger(eventName); 576}); 577</pre> 578 579 <p id="Events-off"> 580 <b class="header">off</b><code>object.off([event], [callback], [context])</code><span class="alias">Alias: unbind</span> 581 <br /> 582 Remove a previously-bound <b>callback</b> function from an object. If no 583 <b>context</b> is specified, all of the versions of the callback with 584 different contexts will be removed. If no 585 callback is specified, all callbacks for the <b>event</b> will be 586 removed. If no event is specified, <i>all</i> event callbacks on the object 587 will be removed. 588 </p> 589 590<pre> 591object.off("change", onChange); // Removes just the onChange callback. 592 593object.off("change"); // Removes all "change" callbacks. 594 595object.off(); // Removes all callbacks on object. 596</pre> 597 598 <p id="Events-trigger"> 599 <b class="header">trigger</b><code>object.trigger(event, [*args])</code> 600 <br /> 601 Trigger callbacks for the given <b>event</b>, or space-delimited list of events. 602 Subsequent arguments to <b>trigger</b> will be passed along to the 603 event callbacks. 604 </p> 605 606 <h2 id="Model">Backbone.Model</h2> 607 608 <p> 609 <b>Models</b> are the heart of any JavaScript application, containing 610 the interactive data as well as a large part of the logic surrounding it: 611 conversions, validations, computed properties, and access control. You 612 extend <b>Backbone.Model</b> with your domain-specific methods, and 613 <b>Model</b> provides a basic set of functionality for managing changes. 614 </p> 615 616 <p> 617 The following is a contrived example, but it demonstrates defining a model 618 with a custom method, setting an attribute, and firing an event keyed 619 to changes in that specific attribute. 620 After running this code once, <tt>sidebar</tt> will be 621 available in your browser's console, so you can play around with it. 622 </p> 623 624<pre class="runnable"> 625var Sidebar = Backbone.Model.extend({ 626 promptColor: function() { 627 var cssColor = prompt("Please enter a CSS color:"); 628 this.set({color: cssColor}); 629 } 630}); 631 632window.sidebar = new Sidebar; 633 634sidebar.on('change:color', function(model, color) { 635 $('#sidebar').css({background: color}); 636}); 637 638sidebar.set({color: 'white'}); 639 640sidebar.promptColor(); 641</pre> 642 643 <p id="Model-extend"> 644 <b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code> 645 <br /> 646 To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b> 647 and provide instance <b>properties</b>, as well as optional 648 <b>classProperties</b> to be attached directly to the constructor function. 649 </p> 650 651 <p> 652 <b>extend</b> correctly sets up the prototype chain, so subclasses created 653 with <b>extend</b> can be further extended and subclassed as far as you like. 654 </p> 655 656<pre> 657var Note = Backbone.Model.extend({ 658 659 initialize: function() { ... }, 660 661 author: function() { ... }, 662 663 coordinates: function() { ... }, 664 665 allowedToEdit: function(account) { 666 return true; 667 } 668 669}); 670 671var PrivateNote = Note.extend({ 672 673 allowedToEdit: function(account) { 674 return account.owns(this); 675 } 676 677}); 678</pre> 679 680 <p class="warning"> 681 Brief aside on <tt>super</tt>: JavaScript does not provide 682 a simple way to call super — the function of the same name defined 683 higher on the prototype chain. If you override a core function like 684 <tt>set</tt>, or <tt>save</tt>, and you want to invoke the 685 parent object's implementation, you'll have to explicitly call it, along these lines: 686 </p> 687 688<pre> 689var Note = Backbone.Model.extend({ 690 set: function(attributes, options) { 691 Backbone.Model.prototype.set.call(this, attributes, options); 692 ... 693 } 694}); 695</pre> 696 697 <p id="Model-constructor"> 698 <b class="header">constructor / initialize</b><code>new Model([attributes])</code> 699 <br /> 700 When creating an instance of a model, you can pass in the initial values 701 of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the 702 model. If you define an <b>initialize</b> function, it will be invoked when 703 the model is created. 704 </p> 705 706<pre> 707new Book({ 708 title: "One Thousand and One Nights", 709 author: "Scheherazade" 710}); 711</pre> 712 713 <p> 714 In rare cases, if you're looking to get fancy, 715 you may want to override <b>constructor</b>, which allows 716 you to replace the actual constructor function for your model. 717 </p> 718 719 <p id="Model-get"> 720 <b class="header">get</b><code>model.get(attribute)</code> 721 <br /> 722 Get the current value of an attribute from the model. For example: 723 <tt>note.get("title")</tt> 724 </p> 725 726 <p id="Model-set"> 727 <b class="header">set</b><code>model.set(attributes, [options])</code> 728 <br /> 729 Set a hash of attributes (one or many) on the model. If any of the attributes 730 change the models state, a <tt>"change"</tt> event will be triggered, unless 731 <tt>{silent: true}</tt> is passed as an option. Change events for specific 732 attributes are also triggered, and you can bind to those as well, for example: 733 <tt>change:title</tt>, and <tt>change:content</tt>. You may also pass 734 individual keys and values. 735 </p> 736 737<pre> 738note.set({title: "March 20", content: "In his eyes she eclipses..."}); 739 740book.set("title", "A Scandal in Bohemia"); 741</pre> 742 743 <p> 744 If the model has a <a href="#Model-validate">validate</a> method, 745 it will be validated before the attributes are set, no changes will 746 occur if the validation fails, and <b>set</b> will return <tt>false</tt>. 747 Otherwise, <b>set</b> returns a reference to the model. 748 You may also pass an <tt>error</tt> 749 callback in the options, which will be invoked instead of triggering an 750 <tt>"error"</tt> event, should validation fail. 751 </p> 752 753 <p id="Model-escape"> 754 <b class="header">escape</b><code>model.escape(attribute)</code> 755 <br /> 756 Similar to <a href="#Model-get">get</a>, but returns the HTML-escaped version 757 of a model's attribute. If you're interpolating data from the model into 758 HTML, using <b>escape</b> to retrieve attributes will prevent 759 <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> attacks. 760 </p> 761 762<pre class="runnable"> 763var hacker = new Backbone.Model({ 764 name: "<script>alert('xss')</script>" 765}); 766 767alert(hacker.escape('name')); 768</pre> 769 770 <p id="Model-has"> 771 <b class="header">has</b><code>model.has(attribute)</code> 772 <br /> 773 Returns <tt>true</tt> if the attribute is set to a non-null or non-undefined 774 value. 775 </p> 776 777<pre> 778if (note.has("title")) { 779 ... 780} 781</pre> 782 783 <p id="Model-unset"> 784 <b class="header">unset</b><code>model.unset(attribute, [options])</code> 785 <br /> 786 Remove an attribute by deleting it from the internal attributes hash. 787 Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option. 788 </p> 789 790 <p id="Model-clear"> 791 <b class="header">clear</b><code>model.clear([options])</code> 792 <br /> 793 Removes all attributes from the model. Fires a <tt>"change"</tt> event unless 794 <tt>silent</tt> is passed as an option. 795 </p> 796 797 <p id="Model-id"> 798 <b class="header">id</b><code>model.id</code> 799 <br /> 800 A special property of models, the <b>id</b> is an arbitrary string 801 (integer id or UUID). If you set the <b>id</b> in the 802 attributes hash, it will be copied onto the model as a direct property. 803 Models can be retrieved by id from collections, and the id is used to generate 804 model URLs by default. 805 </p> 806 807 <p id="Model-idAttribute"> 808 <b class="header">idAttribute</b><code>model.idAttribute</code> 809 <br /> 810 A model's unique identifier is stored under the <tt>id</tt> attribute. 811 If you're directly communicating with a backend (CouchDB, MongoDB) that uses 812 a different unique key, you may set a Model's <tt>idAttribute</tt> to 813 transparently map from that key to <tt>id</tt>. 814 815<pre class="runnable"> 816var Meal = Backbone.Model.extend({ 817 idAttribute: "_id" 818}); 819 820var cake = new Meal({ _id: 1, name: "Cake" }); 821alert("Cake id: " + cake.id); 822</pre> 823 </p> 824 825 <p id="Model-cid"> 826 <b class="header">cid</b><code>model.cid</code> 827 <br /> 828 A special property of models, the <b>cid</b> or client id is a unique identifier 829 automatically assigned to all models when they're first created. Client ids 830 are handy when the model has not yet been saved to the server, and does not 831 yet have its eventual true <b>id</b>, but already needs to be visible in the UI. 832 Client ids take the form: <tt>c1, c2, c3 ...</tt> 833 </p> 834 835 <p id="Model-attributes"> 836 <b class="header">attributes</b><code>model.attributes</code> 837 <br /> 838 The <b>attributes</b> property is the internal hash containing the model's 839 state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying 840 them directly. If you'd like to retrieve and munge a copy of the model's 841 attributes, use <a href="#Model-toJSON">toJSON</a> instead. 842 </p> 843 844 <p id="Model-defaults"> 845 <b class="header">defaults</b><code>model.defaults or model.defaults()</code> 846 <br /> 847 The <b>defaults</b> hash (or function) can be used to specify the default 848 attributes for your model. When creating an instance of the model, 849 any unspecified attributes will be set to their default value. 850 </p> 851 852<pre class="runnable"> 853var Meal = Backbone.Model.extend({ 854 defaults: { 855 "appetizer": "caesar salad", 856 "entree": "ravioli", 857 "dessert": "cheesecake" 858 } 859}); 860 861alert("Dessert will be " + (new Meal).get('dessert')); 862</pre> 863 864 <p class="warning"> 865 Remember that in JavaScript, objects are passed by reference, so if you 866 include an object as a default value, it will be shared among all instances. 867 </p> 868 869 <p id="Model-toJSON"> 870 <b class="header">toJSON</b><code>model.toJSON()</code> 871 <br /> 872 Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification. 873 This can be used for persistence, serialization, or for augmentation before 874 being handed off to a view. The name of this method is a bit confusing, as 875 it doesn't actually return a JSON string — but I'm afraid that it's 876 the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>. 877 </p> 878 879<pre class="runnable"> 880var artist = new Backbone.Model({ 881 firstName: "Wassily", 882 lastName: "Kandinsky" 883}); 884 885artist.set({birthday: "December 16, 1866"}); 886 887alert(JSON.stringify(artist)); 888</pre> 889 890 <p id="Model-fetch"> 891 <b class="header">fetch</b><code>model.fetch([options])</code> 892 <br /> 893 Resets the model's state from the server. Useful if the model has never 894 been populated with data, or if you'd like to ensure that you have the 895 latest server state. A <tt>"change"</tt> event will be triggered if the 896 server's state differs from the current attributes. Accepts 897 <tt>success</tt> and <tt>error</tt> callbacks in the options hash, which 898 are passed <tt>(model, response)</tt> as arguments. 899 </p> 900 901<pre> 902// Poll every 10 seconds to keep the channel model up-to-date. 903setInterval(function() { 904 channel.fetch(); 905}, 10000); 906</pre> 907 908 <p id="Model-save"> 909 <b class="header">save</b><code>model.save([attributes], [options])</code> 910 <br /> 911 Save a model to your database (or alternative persistence layer), 912 by delegating to <a href="#Sync">Backbone.sync</a>. The <b>attributes</b> 913 hash (as in <a href="#Model-set">set</a>) should contain the attributes 914 you'd like to change — keys that aren't mentioned won't be altered — but, 915 a <i>complete representation</i> of the resource will be sent to the server. 916 As with <tt>set</tt>, you may pass individual keys and values instead of a hash. 917 If the model has a <a href="#Model-validate">validate</a> 918 method, and validation fails, the model will not be saved. If the model 919 <a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt> 920 (HTTP <tt>POST</tt>), if the model already 921 exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>). 922 </p> 923 924 <p> 925 Calling <tt>save</tt> with new attributes will cause a <tt>"change"</tt> 926 event immediately, and a <tt>"sync"</tt> event after the server has acknowledged 927 the successful change. Pass <tt>{wait: true}</tt> if you'd like to wait 928 for the server before setting the new attributes on the model. 929 </p> 930 931 <p> 932 In the following example, notice how our overridden version 933 of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request 934 the first time the model is saved and an <tt>"update"</tt> 935 request the second time. 936 </p> 937 938<pre class="runnable"> 939Backbone.sync = function(method, model) { 940 alert(method + ": " + JSON.stringify(model)); 941 model.id = 1; 942}; 943 944var book = new Backbone.Model({ 945 title: "The Rough Riders", 946 author: "Theodore Roosevelt" 947}); 948 949book.save(); 950 951book.save({author: "Teddy"}); 952</pre> 953 954 <p> 955 <b>save</b> accepts <tt>success</tt> and <tt>error</tt> callbacks in the 956 options hash, which are passed <tt>(model, response)</tt> as arguments. 957 The <tt>error</tt> callback will also be invoked if the model has a 958 <tt>validate</tt> method, and validation fails. If a server-side 959 validation fails, return a non-<tt>200</tt> HTTP response code, along with 960 an error response in text or JSON. 961 </p> 962 963<pre> 964book.save("author", "F.D.R.", {error: function(){ ... }}); 965</pre> 966 967 <p id="Model-destroy"> 968 <b class="header">destroy</b><code>model.destroy([options])</code> 969 <br /> 970 Destroys the model on the server by delegating an HTTP <tt>DELETE</tt> 971 request to <a href="#Sync">Backbone.sync</a>. Accepts 972 <tt>success</tt> and <tt>error</tt> callbacks in the options hash. 973 Triggers a <tt>"destroy"</tt> event on the model, which will bubble up 974 through any collections that contain it, and a <tt>"sync"</tt> event, after 975 the server has successfully acknowledged the model's deletion. Pass 976 <tt>{wait: true}</tt> if you'd like to wait for the server to respond 977 before removing the model from the collection. 978 </p> 979 980<pre> 981book.destroy({success: function(model, response) { 982 ... 983}}); 984</pre> 985 986 <p id="Model-validate"> 987 <b class="header">validate</b><code>model.validate(attributes)</code> 988 <br /> 989 This method is left undefined, and you're encouraged to override it with 990 your custom validation logic, if you have any that can be performed 991 in JavaScript. <b>validate</b> is called before <tt>set</tt> and 992 <tt>save</tt>, and is passed the attributes that are about to be updated. 993 If the model and attributes are valid, don't return anything from <b>validate</b>; 994 if the attributes are invalid, return an error of your choosing. It 995 can be as simple as a string error message to be displayed, or a complete 996 error object that describes the error programmatically. <tt>set</tt> and 997 <tt>save</tt> will not continue if <b>validate</b> returns an error. 998 Failed validations trigger an <tt>"error"</tt> event. 999 </p> 1000 1001<pre class="runnable"> 1002var Chapter = Backbone.Model.extend({ 1003 validate: function(attrs) { 1004 if (attrs.end < attrs.start) { 1005 return "can't end before it starts"; 1006 } 1007 } 1008}); 1009 1010var one = new Chapter({ 1011 title : "Chapter One: The Beginning" 1012}); 1013 1014one.on("error", function(model, error) { 1015 alert(model.get("title") + " " + error); 1016}); 1017 1018one.set({ 1019 start: 15, 1020 end: 10 1021}); 1022</pre> 1023 1024 <p> 1025 <tt>"error"</tt> events are useful for providing coarse-grained error 1026 messages at the model or collection level, but if you have a specific view 1027 that can better handle the error, you may override and suppress the event 1028 by passing an <tt>error</tt> callback directly: 1029 </p> 1030 1031<pre> 1032account.set({access: "unlimited"}, { 1033 error: function(model, error) { 1034 alert(error); 1035 } 1036}); 1037</pre> 1038 1039 <p id="Model-isValid"> 1040 <b class="header">isValid</b><code>model.isValid()</code> 1041 <br /> 1042 Models may enter an invalid state if you make changes to them silently 1043 ... useful when dealing with form input. Call <tt>model.isValid()</tt> 1044 to check if the model is currently in a valid state, according to your 1045 <tt>validate</tt> function. 1046 </p> 1047 1048 <p id="Model-url"> 1049 <b class="header">url</b><code>model.url()</code> 1050 <br /> 1051 Returns the relative URL where the model's resource would be located on 1052 the server. If your models are located somewhere else, override this method 1053 with the correct logic. Generates URLs of the form: <tt>"/[collection.url]/[id]"</tt>, 1054 falling back to <tt>"/[urlRoot]/id"</tt> if the model is not part of a collection. 1055 </p> 1056 1057 <p> 1058 Delegates to <a href="#Collection-url">Collection#url</a> to generate the 1059 URL, so make sure that you have it defined, or a <a href="#Model-urlRoot">urlRoot</a> 1060 property, if all models of this class share a common root URL. 1061 A model with an id of <tt>101</tt>, stored in a 1062 <a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/documents/7/notes"</tt>, 1063 would have this URL: <tt>"/documents/7/notes/101"</tt> 1064 </p> 1065 1066 <p id="Model-urlRoot"> 1067 <b class="header">urlRoot</b><code>model.urlRoot</code> 1068 <br /> 1069 Specify a <tt>urlRoot</tt> if you're using a model outside of a collection, 1070 to enable the default <a href="#Model-url">url</a> function to generate 1071 URLs based on the model id. <tt>"/[urlRoot]/id"</tt><br /> 1072 Note that <tt>urlRoot</tt> may also be defined as a function. 1073 </p> 1074 1075<pre class="runnable"> 1076var Book = Backbone.Model.extend({urlRoot : '/books'}); 1077 1078var solaris = new Book({id: "1083-lem-solaris"}); 1079 1080alert(solaris.url()); 1081</pre> 1082 1083 <p id="Model-parse"> 1084 <b class="header">parse</b><code>model.parse(response)</code> 1085 <br /> 1086 <b>parse</b> is called whenever a model's data is returned by the 1087 server, in <a href="#Model-fetch">fetch</a>, and <a href="#Model-save">save</a>. 1088 The function is passed the raw <tt>response</tt> object, and should return 1089 the attributes hash to be <a href="#Model-set">set</a> on the model. The 1090 default implementation is a no-op, simply passing through the JSON response. 1091 Override this if you need to work with a preexisting API, or better namespace 1092 your responses. 1093 </p> 1094 1095 <p> 1096 If you're working with a Rails backend, you'll notice that Rails' default 1097 <tt>to_json</tt> implementation includes a model's attributes under a 1098 namespace. To disable this behavior for seamless Backbone integration, set: 1099 </p> 1100 1101<pre> 1102ActiveRecord::Base.include_root_in_json = false 1103</pre> 1104 1105 <p id="Model-clone"> 1106 <b class="header">clone</b><code>model.clone()</code> 1107 <br /> 1108 Returns a new instance of the model with identical attributes. 1109 </p> 1110 1111 <p id="Model-isNew"> 1112 <b class="header">isNew</b><code>model.isNew()</code> 1113 <br /> 1114 Has this model been saved to the server yet? If the model does not yet have 1115 an <tt>id</tt>, it is considered to be new. 1116 </p> 1117 1118 <p id="Model-change"> 1119 <b class="header">change</b><code>model.change()</code> 1120 <br /> 1121 Manually trigger the <tt>"change"</tt> event and a <tt>"change:attribute"</tt> 1122 event for each attribute that has changed. If you've been passing 1123 <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to 1124 aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt> 1125 when you're all finished. 1126 </p> 1127 1128 <p id="Model-hasChanged"> 1129 <b class="header">hasChanged</b><code>model.hasChanged([attribute])</code> 1130 <br /> 1131 Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b> 1132 is passed, returns <tt>true</tt> if that specific attribute has changed. 1133 </p> 1134 1135 <p class="warning"> 1136 Note that this method, and the following change-related ones, 1137 are only useful during the course of a <tt>"change"</tt> event. 1138 </p> 1139 1140<pre> 1141book.on("change", function() { 1142 if (book.hasChanged("title")) { 1143 ... 1144 } 1145}); 1146</pre> 1147 1148 <p id="Model-changedAttributes"> 1149 <b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code> 1150 <br /> 1151 Retrieve a hash of only the model's attributes that have changed. Optionally, 1152 an external <b>attributes</b> hash can be passed in, returning 1153 the attributes in that hash which differ from the model. This can be used 1154 to figure out which portions of a view should be updated, or what calls 1155 need to be made to sync the changes to the server. 1156 </p> 1157 1158 <p id="Model-previous"> 1159 <b class="header">previous</b><code>model.previous(attribute)</code> 1160 <br /> 1161 During a <tt>"change"</tt> event, this method can be used to get the 1162 previous value of a changed attribute. 1163 </p> 1164 1165<pre class="runnable"> 1166var bill = new Backbone.Model({ 1167 name: "Bill Smith" 1168}); 1169 1170bill.on("change:name", function(model, name) { 1171 alert("Changed name from " + bill.previous("name") + " to " + name); 1172}); 1173 1174bill.set({name : "Bill Jones"}); 1175</pre> 1176 1177 <p id="Model-previousAttributes"> 1178 <b class="header">previousAttributes</b><code>model.previousAttributes()</code> 1179 <br /> 1180 Return a copy of the model's previous attributes. Useful for getting a 1181 diff between versions of a model, or getting back to a valid state after 1182 an error occurs. 1183 </p> 1184 1185 <h2 id="Collection">Backbone.Collection</h2> 1186 1187 <p> 1188 Collections are ordered sets of models. You can bind <tt>"change"</tt> events 1189 to be notified when any model in the collection has been modified, 1190 listen for <tt>"add"</tt> and <tt>"remove"</tt> events, <tt>fetch</tt> 1191 the collection from the server, and use a full suite of 1192 <a href="#Collection-Underscore-Methods">Underscore.js methods</a>. 1193 </p> 1194 1195 <p> 1196 Any event that is triggered on a model in a collection will also be 1197 triggered on the collection directly, for convenience. 1198 This allows you to listen for changes to specific attributes in any 1199 model in a collection, for example: 1200 <tt>Documents.on("change:selected", ...)</tt> 1201 </p> 1202 1203 <p id="Collection-extend"> 1204 <b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code> 1205 <br /> 1206 To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>, 1207 providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached 1208 directly to the collection's constructor function. 1209 </p> 1210 1211 <p id="Collection-model"> 1212 <b class="header">model</b><code>collection.model</code> 1213 <br /> 1214 Override this property to specify the model class that the collection 1215 contains. If defined, you can pass raw attributes objects (and arrays) to 1216 <a href="#Collection-add">add</a>, <a href="#Collection-create">create</a>, 1217 and <a href="#Collection-reset">reset</a>, and the attributes will be 1218 converted into a model of the proper type. 1219 </p> 1220 1221<pre> 1222var Library = Backbone.Collection.extend({ 1223 model: Book 1224}); 1225</pre> 1226 1227 <p id="Collection-constructor"> 1228 <b class="header">constructor / initialize</b><code>new Collection([models], [options])</code> 1229 <br /> 1230 When creating a Collection, you may choose to pass in the initial array of <b>models</b>. 1231 The collection's <a href="#Collection-comparator">comparator</a> function 1232 may be included as an option. If you define an <b>initialize</b> function, it will be 1233 invoked when the collection is created. 1234 </p> 1235 1236<pre> 1237var tabs = new TabSet([tab1, tab2, tab3]); 1238</pre> 1239 1240 <p id="Collection-models"> 1241 <b class="header">models</b><code>collection.models</code> 1242 <br /> 1243 Raw access to the JavaScript array of models inside of the collection. Usually you'll 1244 want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b> 1245 to access model objects, but occasionally a direct reference to the array 1246 is desired. 1247 </p> 1248 1249 <p id="Collection-toJSON"> 1250 <b class="header">toJSON</b><code>collection.toJSON()</code> 1251 <br /> 1252 Return an array containing the attributes hash of each model in the 1253 collection. This can be used to serialize and persist the 1254 collection as a whole. The name of this method is a bit confusing, because 1255 it conforms to 1256 <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript's JSON API</a>. 1257 </p> 1258 1259<pre class="runnable"> 1260var collection = new Backbone.Collection([ 1261 {name: "Tim", age: 5}, 1262 {name: "Ida", age: 26}, 1263 {name: "Rob", age: 55} 1264]); 1265 1266alert(JSON.stringify(collection)); 1267</pre> 1268 1269 <p id="Collection-Underscore-Methods"> 1270 <b class="header">Underscore Methods (28)</b> 1271 <br /> 1272 Backbone proxies to <b>Underscore.js</b> to provide 28 iteration functions 1273 on <b>Backbone.Collection</b>. They aren't all documented here, but 1274 you can take a look at the Underscore documentation for the full details… 1275 </p> 1276 1277 <ul class="small"> 1278 <li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li> 1279 <li><a href="http://documentcloud.github.com/underscore/#map">map</a></li> 1280 <li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li> 1281 <li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li> 1282 <li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li> 1283 <li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li> 1284 <li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li> 1285 <li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li> 1286 <li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li> 1287 <li><a href="http://documentcloud.github.com/underscore/#include">include</a></li> 1288 <li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li> 1289 <li><a href="http://documentcloud.github.com/underscore/#max">max</a></li> 1290 <li><a href="http://documentcloud.github.com/underscore/#min">min</a></li> 1291 <li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li> 1292 <li><a href="http://documentcloud.github.com/underscore/#groupBy">groupBy</a></li> 1293 <li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li> 1294 <li><a href="http://documentcloud.github.com/underscore/#shuffle">shuffle</a></li> 1295 <li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li> 1296 <li><a href="http://documentcloud.github.com/underscore/#size">size</a></li> 1297 <li><a href="http://documentcloud.github.com/underscore/#first">first</a></li> 1298 <li><a href="http://documentcloud.github.com/underscore/#initial">initial</a></li> 1299 <li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li> 1300 <li><a href="http://documentcloud.github.com/underscore/#last">last</a></li> 1301 <li><a href="http://documentcloud.github.com/underscore/#without">without</a></li> 1302 <li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li> 1303 <li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li> 1304 <li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li> 1305 <li><a href="http://documentcloud.github.com/underscore/#chain">chain</a></li> 1306 </ul> 1307 1308<pre> 1309Books.each(function(book) { 1310 book.publish(); 1311}); 1312 1313var titles = Books.map(function(book) { 1314 return book.get("title"); 1315}); 1316 1317var publishedBooks = Books.filter(function(book) { 1318 return book.get("published") === true; 1319}); 1320 1321var alphabetical = Books.sortBy(function(book) { 1322 return book.author.get("name").toLowerCase(); 1323}); 1324</pre> 1325 1326 <p id="Collection-add"> 1327 <b class="header">add</b><code>collection.add(models, [options])</code> 1328 <br /> 1329 Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt> 1330 event, which you can pass <tt>{silent: true}</tt> to suppress. If a 1331 <a href="#Collection-model">model</a> property is defined, you may also pass 1332 raw attributes objects, and have them be vivified as instances of the model. 1333 Pass <tt>{at: index}</tt> to splice the model into the collection at the 1334 specified <tt>index</tt>. Likewise, if you're a callback listening to a 1335 collection's <tt>"add"</tt> event, <tt>options.index</tt> will tell you the 1336 index at which the model is being added to the collection. 1337 </p> 1338 1339<pre class="runnable"> 1340var ships = new Backbone.Collection; 1341 1342ships.on("add", function(ship) { 1343 alert("Ahoy " + ship.get("name") + "!"); 1344}); 1345 1346ships.add([ 1347 {name: "Flying Dutchman"}, 1348 {name: "Black Pearl"} 1349]); 1350</pre> 1351 1352 <p id="Collection-remove"> 1353 <b class="header">remove</b><code>collection.remove(models, [options])</code> 1354 <br /> 1355 Remove a model (or an array of models) from the collection. Fires a 1356 <tt>"remove"</tt> event, which you can use <tt>silent</tt> 1357 to suppress. If you're a callback listening to the <tt>"remove"</tt> event, 1358 the index at which the model is being removed from the collection is available 1359 as <tt>options.index</tt>. 1360 </p> 1361 1362 <p id="Collection-get"> 1363 <b class="header">get</b><code>collection.get(id)</code> 1364 <br /> 1365 Get a model from a collection, specified by <b>id</b>. 1366 </p> 1367 1368<pre> 1369var book = Library.get(110); 1370</pre> 1371 1372 <p id="Collection-getByCid"> 1373 <b class="header">getByCid</b><code>collection.getByCid(cid)</code> 1374 <br /> 1375 Get a model from a collection, specified by client id. The client id 1376 is the <tt>.cid</tt> property of the model, automatically assigned whenever 1377 a model is created. Useful for models which have not yet been saved to 1378 the server, and do not yet have true ids. 1379 </p> 1380 1381 <p id="Collection-at"> 1382 <b class="header">at</b><code>collection.at(index)</code> 1383 <br /> 1384 Get a model from a collection, specified by index. Useful if your collection 1385 is sorted, and if your collection isn't sorted, <b>at</b> will still 1386 retrieve models in insertion order. 1387 </p> 1388 1389 <p id="Collection-length"> 1390 <b class="header">length</b><code>collection.length</code> 1391 <br /> 1392 Like an array, a Collection maintains a <tt>length</tt> property, counting 1393 the number of models it contains. 1394 </p> 1395 1396 <p id="Collection-comparator"> 1397 <b class="header">comparator</b><code>collection.comparator</code> 1398 <br /> 1399 By default there is no <b>comparator</b> function on a collection. 1400 If you define a comparator, it will be used to maintain 1401 the collection in sorted order. This means that as models are added, 1402 they are inserted at the correct index in <tt>collection.models</tt>. 1403 Comparator function can be defined as either a 1404 <a href="http://underscorejs.org/#sortBy">sortBy</a> 1405 (pass a function that takes a single argument), 1406 or as a 1407 <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort">sort</a> 1408 (pass a comparator function that expects two arguments). 1409 </p> 1410 1411 <p> 1412 "sort" comparator functions take a model and return a numeric or string 1413 value by which the model should be ordered relative to others. 1414 "sortBy" comparator functions take two models, and return <tt>-1</tt> if 1415 the first model should come before the second, <tt>0</tt> if they are of 1416 the same rank and <tt>1</tt> if the first model should come after. 1417 </p> 1418 1419 <p> 1420 Note how even though all of the chapters in this example are added backwards, 1421 they come out in the proper order: 1422 </p> 1423 1424<pre class="runnable"> 1425var Chapter = Backbone.Model; 1426var chapters = new Backbone.Collection; 1427 1428chapters.comparator = function(chapter) { 1429 return chapter.get("page"); 1430}; 1431 1432chapters.add(new Chapter({page: 9, title: "The End"})); 1433chapters.add(new Chapter({page: 5, title: "The Middle"})); 1434chapters.add(new Chapter({page: 1, title: "The Beginning"})); 1435 1436alert(chapters.pluck('title')); 1437</pre> 1438 1439 <p class="warning"> 1440 Collections with comparator functions will not automatically re-sort if you 1441 later change model attributes, so you may wish to call <tt>sort</tt> after 1442 changing model attributes that would affect the order. 1443 </p> 1444 1445 <p id="Collection-sort"> 1446 <b class="header">sort</b><code>collection.sort([options])</code> 1447 <br /> 1448 Force a collection to re-sort itself. You don't need to call this under 1449 normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function 1450 will maintain itself in proper sort order at all times. Calling <b>sort</b> 1451 triggers the collection's <tt>"reset"</tt> event, unless silenced by passing 1452 <tt>{silent: true}</tt> 1453 </p> 1454 1455 <p id="Collection-pluck"> 1456 <b class="header">pluck</b><code>collection.pluck(attribute)</code> 1457 <br /> 1458 Pluck an attribute from each model in the collection. Equivalent to calling 1459 <tt>map</tt>, and returning a single attribute from the iterator. 1460 </p> 1461 1462<pre class="runnable"> 1463var stooges = new Backbone.Collection([ 1464 new Backbone.Model({name: "Curly"}), 1465 new Backbone.Model({name: "Larry"}), 1466 new Backbone.Model({name: "Moe"}) 1467]); 1468 1469var names = stooges.pluck("name"); 1470 1471alert(JSON.stringify(names)); 1472</pre> 1473 1474 <p id="Collection-url"> 1475 <b class="header">url</b><code>collection.url or collection.url()</code> 1476 <br /> 1477 Set the <b>url</b> property (or function) on a collection to reference 1478 its location on the server. Models within the collection will use <b>url</b> 1479 to construct URLs of their own. 1480 </p> 1481 1482<pre> 1483var Notes = Backbone.Collection.extend({ 1484 url: '/notes' 1485}); 1486 1487// Or, something more sophisticated: 1488 1489var Notes = Backbone.Collection.extend({ 1490 url: function() { 1491 return this.document.url() + '/notes'; 1492 } 1493}); 1494</pre> 1495 1496 <p id="Collection-parse"> 1497 <b class="header">parse</b><code>collection.parse(response)</code> 1498 <br /> 1499 <b>parse</b> is called by Backbone whenever a collection's models are 1500 returned by the server, in <a href="#Collection-fetch">fetch</a>. 1501 The function is passed the raw <tt>response</tt> object, and should return 1502 the array of model attributes to be <a href="#Collection-add">added</a> 1503 to the collection. The default implementation is a no-op, simply passing 1504 through the JSON response. Override this if you need to work with a 1505 preexisting API, or better namespace your responses. Note that afterwards, 1506 if your model class already has a <tt>parse</tt> function, it will be 1507 run against each fetched model. 1508 </p> 1509 1510<pre> 1511var Tweets = Backbone.Collection.extend({ 1512 // The Twitter Search API returns tweets under "results". 1513 parse: function(response) { 1514 return response.results; 1515 } 1516}); 1517</pre> 1518 1519 <p id="Collection-fetch"> 1520 <b class="header">fetch</b><code>collection.fetch([options])</code> 1521 <br /> 1522 Fetch the default set of models for this collection from the server, 1523 resetting the collection when they arrive. The <b>options</b> hash takes 1524 <tt>success</tt> and <tt>error</tt> 1525 callbacks which will be passed <tt>(collection, response)</tt> as arguments. 1526 When the model data returns from the server, the collection will 1527 <a href="#Collection-reset">reset</a>. 1528 Delegates to <a href="#Sync">Backbone.sync</a> 1529 under the covers, for custom persistence strategies. 1530 The server handler for <b>fetch</b> requests should return a JSON array of 1531 models. 1532 </p> 1533 1534<pre class="runnable"> 1535Backbone.sync = function(method, model) { 1536 alert(method + ": " + model.url); 1537}; 1538 1539var Accounts = new Backbone.Collection; 1540Accounts.url = '/accounts'; 1541 1542Accounts.fetch(); 1543</pre> 1544 1545 <p> 1546 If you'd like to add the incoming models to the current collection, instead 1547 of replacing the collection's contents, pass <tt>{add: true}</tt> as an 1548 option to <b>fetch</b>. 1549 </p> 1550 1551 <p> 1552 <b>jQuery.ajax</b> options can also be passed directly as <b>fetch</b> options, 1553 so to fetch a specific page of a paginated collection: 1554 <tt>Documents.fetch({data: {page: 3}})</tt> 1555 </p> 1556 1557 <p> 1558 Note that <b>fetch</b> should not be used to populate collections on 1559 page load — all models needed at load time should already be 1560 <a href="#FAQ-bootstrap">bootstrapped</a> in to place. <b>fetch</b> is 1561 intended for lazily-loading models for interfaces that are not needed 1562 immediately: for example, documents with collections of notes that may be 1563 toggled open and closed. 1564 </p> 1565 1566 <p id="Collection-reset"> 1567 <b class="header">reset</b><code>collection.reset(models, [options])</code> 1568 <br /> 1569 Adding and removing models one at a time is all well and good, but sometimes 1570 you have so many models to change that you'd rather just update the collection 1571 in bulk. Use <b>reset</b> to replace a collection with a new list 1572 of models (or attribute hashes), triggering a single <tt>"reset"</tt> event 1573 at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"reset"</tt> event. 1574 Using reset with no arguments is useful as a way to empty the collection. 1575 </p> 1576 1577 <p> 1578 Here's an example using <b>reset</b> to bootstrap a collection during initial page load, 1579 in a Rails application. 1580 </p> 1581 1582<pre> 1583<script> 1584 Accounts.reset(<%= @accounts.to_json %>); 1585</script> 1586</pre> 1587 1588 <p> 1589 Calling <tt>collection.reset()</tt> without passing any models as arguments 1590 will empty the entire collection. 1591 </p> 1592 1593 <p id="Collection-create"> 1594 <b class="header">create</b><code>collection.create(attributes, [options])</code> 1595 <br /> 1596 Convenience to create a new instance of a model within a collection. 1597 Equivalent to instantiating a model with a hash of attributes, 1598 saving the model to the server, and adding the model to the set after being 1599 successfully created. Returns 1600 the model, or <tt>false</tt> if a validation error prevented the 1601 model from being created. In order for this to work, you should set the 1602 <a href="#Collection-model">model</a> property of the collection. 1603 The <b>create</b> method can accept either an attributes hash or an 1604 existing, unsaved model object. 1605 </p> 1606 1607 <p> 1608 Creating a model will cause an immediate <tt>"add"</tt> event to be 1609 triggered on the collection, as well as a <tt>"sync"</tt> event, once the 1610 model has been successfully created on the server. Pass <tt>{wait: true}</tt> 1611 if you'd like to wait for the server before adding the new model to the collection. 1612 </p> 1613 1614<pre> 1615var Library = Backbone.Collection.extend({ 1616 model: Book 1617}); 1618 1619var NYPL = new Library; 1620 1621var othello = NYPL.create({ 1622 title: "Othello", 1623 author: "William Shakespeare" 1624}); 1625</pre> 1626 1627 <h2 id="Router">Backbone.Router</h2> 1628 1629 <p> 1630 Web applications often provide linkable, bookmarkable, shareable URLs for 1631 important locations in the app. Until recently, hash fragments 1632 (<tt>#page</tt>) were used to provide these permalinks, but with the 1633 arrival of the History API, it's now possible to use standard URLs (<tt>/page</tt>). 1634 <b>Backbone.Router</b> provides methods for routing client-side pages, and 1635 connecting them to actions and events. For browsers which don't yet support 1636 the History API, the Router handles graceful fallback and transparent 1637 translation to the fragment version of the URL. 1638 </p> 1639 1640 <p> 1641 During page load, after your application has finished creating all of its routers, 1642 be sure to call <tt>Backbone.history.start()</tt>, or 1643 <tt>Backbone.history.start({pushState: true})</tt> to route the initial URL. 1644 </p> 1645 1646 <p id="Router-extend"> 1647 <b class="header">extend</b><code>Backbone.Router.extend(properties, [classProperties])</code> 1648 <br /> 1649 Get started by creating a custom router class. Define actions that are 1650 triggered when certain URL fragments are 1651 matched, and provide a <a href="#Router-routes">routes</a> hash 1652 that pairs routes to actions. Note that you'll want to avoid using a 1653 leading slash in your route definitions: 1654 </p> 1655 1656<pre> 1657var Workspace = Backbone.Router.extend({ 1658 1659 routes: { 1660 "help": "help", // #help 1661 "search/:query": "search", // #search/kiwis 1662 "search/:query/p:page": "search" // #search/kiwis/p7 1663 }, 1664 1665 help: function() { 1666 ... 1667 }, 1668 1669 search: function(query, page) { 1670 ... 1671 } 1672 1673}); 1674</pre> 1675 1676 <p id="Router-routes"> 1677 <b class="header">routes</b><code>router.routes</code> 1678 <br /> 1679 The routes hash maps URLs with parameters to functions on your router, 1680 similar to the <a href="#View">View</a>'s <a href="#View-delegateEvents">events hash</a>. 1681 Routes can contain parameter parts, <tt>:param</tt>, which match a single URL 1682 component between slashes; and splat parts <tt>*splat</tt>, which can match 1683 any number of URL components. 1684 </p> 1685 1686 <p> 1687 For example, a route of <tt>"search/:query/p:page"</tt> will match 1688 a fragment of <tt>#search/obama/p2</tt>, passing <tt>"obama"</tt> 1689 and <tt>"2"</tt> to the action. A route of <tt>"file/*path"</tt> will 1690 match <tt>#file/nested/folder/file.txt</tt>, 1691 passing <tt>"nested/folder/file.txt"</tt> to the action. 1692 </p> 1693 1694 <p> 1695 When the visitor presses the back button, or enters a URL, and a particular 1696 route is matched, the name of the action will be fired as an 1697 <a href="#Events">event</a>, so that other objects can listen to the router, 1698 and be notified. In the following example, visiting <tt>#help/uploading</tt> 1699 will fire a <tt>route:help</tt> event from the router. 1700 </p> 1701 1702<pre> 1703routes: { 1704 "help/:page": "help", 1705 "download/*path": "download", 1706 "folder/:name": "openFolder", 1707 "folder/:name-:mode": "openFolder" 1708} 1709</pre> 1710 1711<pre> 1712router.on("route:help", function(page) { 1713 ... 1714}); 1715</pre> 1716 1717 <p id="Router-constructor"> 1718 <b class="header">constructor / initialize</b><code>new Router([options])</code> 1719 <br /> 1720 When creating a new router, you may pass its 1721 <a href="#Router-routes">routes</a> hash directly as an option, if you 1722 choose. All <tt>options</tt> will also be passed to your <tt>initialize</tt> 1723 function, if defined. 1724 </p> 1725 1726 <p id="Router-route"> 1727 <b class="header">route</b><code>router.route(route, name, [callback])</code> 1728 <br /> 1729 Manually create a route for the router, The <tt>route</tt> argument may 1730 be a <a href="#Router-routes">routing string</a> or regular expression. 1731 Each matching capture from the route or regular expression will be passed as 1732 an argument to the callback. The <tt>name</tt> argument will be triggered as 1733 a <tt>"route:name"</tt> event whenever the route is matched. If the 1734 <tt>callback</tt> argument is omitted <tt>router[name]</tt> wil