forked from jashkenas/backbone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1318 lines (1138 loc) · 45.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Backbone.js</title>
<style>
body {
font-size: 14px;
line-height: 22px;
font-family: Helvetica Neue, Helvetica, Arial;
background: #f4f4f4 url(docs/images/background.png);
}
.interface {
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
}
div#sidebar {
background: #fff;
position: fixed;
top: 0; left: 0; bottom: 0;
width: 200px;
overflow-y: auto;
overflow-x: hidden;
padding: 15px 0 30px 30px;
border-right: 1px solid #ddd;
box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
}
a.toc_title, a.toc_title:visited {
display: block;
color: black;
font-weight: bold;
margin-top: 15px;
}
div.toc_title:hover {
text-decoration: underline;
}
ul.toc_section {
font-size: 11px;
line-height: 14px;
margin: 5px 0 0 0;
padding-left: 0px;
list-style-type: none;
font-family: Lucida Grande;
}
.toc_section li {
cursor: pointer;
margin: 0 0 3px 0;
}
.toc_section li a {
color: black;
}
div.container {
position: relative;
width: 550px;
margin: 40px 0 50px 260px;
}
div.run {
position: absolute;
right: 15px;
width: 26px; height: 18px;
background: url('docs/images/arrows.png') no-repeat -26px 0;
}
div.run:active {
background-position: -51px 0;
}
p, div.container ul {
margin: 20px 0;
width: 550px;
}
div.container ul {
list-style: circle;
font-size: 12px;
padding-left: 15px;
}
a, a:visited {
color: #444;
text-decoration: none;
}
a:active, a:hover {
color: #000;
text-decoration: underline;
}
a img {
border: 0;
}
h1, h2, h3, h4, h5, h6 {
padding-top: 20px;
}
h2 {
font-size: 20px;
}
b.header {
font-size: 16px;
line-height: 30px;
}
span.alias {
font-size: 14px;
font-style: italic;
margin-left: 20px;
}
table {
margin: 15px 0 0; padding: 0;
}
tr, td {
margin: 0; padding: 0;
}
td {
padding: 0px 15px 5px 0;
}
code, pre, tt {
font-family: Monaco, Consolas, "Lucida Console", monospace;
font-size: 12px;
line-height: 18px;
}
tt {
padding: 0px 3px;
background: #fff;
border: 1px solid #ddd;
zoom: 1;
}
code {
margin-left: 20px;
}
pre {
font-size: 12px;
padding: 2px 0 2px 15px;
border: 4px solid #bbb; border-top: 0; border-bottom: 0;
margin: 0px 0 30px;
}
</style>
</head>
<body>
<div id="sidebar" class="interface">
<a class="toc_title" href="#">
Backbone.js
</a>
<a class="toc_title" href="#Introduction">
Introduction
</a>
<a class="toc_title" href="#Events">
Events
</a>
<ul class="toc_section">
<li>– <a href="#Events-bind">bind</a></li>
<li>– <a href="#Events-unbind">unbind</a></li>
<li>– <a href="#Events-trigger">trigger</a></li>
</ul>
<a class="toc_title" href="#Model">
Model
</a>
<ul class="toc_section">
<li>– <a href="#Model-extend">extend</a></li>
<li>– <a href="#Model-constructor">constructor / initialize</a></li>
<li>– <a href="#Model-get">get</a></li>
<li>– <a href="#Model-set">set</a></li>
<li>– <a href="#Model-unset">unset</a></li>
<li>– <a href="#Model-id">id</a></li>
<li>– <a href="#Model-cid">cid</a></li>
<li>– <a href="#Model-attributes">attributes</a></li>
<li>- <a href="#Model-toJSON">toJSON</a></li>
<li>– <a href="#Model-save">save</a></li>
<li>– <a href="#Model-destroy">destroy</a></li>
<li>– <a href="#Model-validate">validate</a></li>
<li>– <a href="#Model-url">url</a></li>
<li>– <a href="#Model-clone">clone</a></li>
<li>– <a href="#Model-isNew">isNew</a></li>
<li>– <a href="#Model-change">change</a></li>
<li>– <a href="#Model-hasChanged">hasChanged</a></li>
<li>– <a href="#Model-changedAttributes">changedAttributes</a></li>
<li>– <a href="#Model-previous">previous</a></li>
<li>– <a href="#Model-previousAttributes">previousAttributes</a></li>
</ul>
<a class="toc_title" href="#Collection">
Collection
</a>
<ul class="toc_section">
<li>– <a href="#Collection-extend">extend</a></li>
<li>– <a href="#Collection-constructor">constructor / initialize</a></li>
<li>– <a href="#Collection-models">models</a></li>
<li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (24)</b></a></li>
<li>– <a href="#Collection-add">add</a></li>
<li>– <a href="#Collection-remove">remove</a></li>
<li>– <a href="#Collection-get">get</a></li>
<li>– <a href="#Collection-getByCid">getByCid</a></li>
<li>– <a href="#Collection-at">at</a></li>
<li>– <a href="#Collection-length">length</a></li>
<li>– <a href="#Collection-comparator">comparator</a></li>
<li>– <a href="#Collection-sort">sort</a></li>
<li>– <a href="#Collection-pluck">pluck</a></li>
<li>– <a href="#Model-url">url</a></li>
<li>– <a href="#Collection-refresh">refresh</a></li>
<li>– <a href="#Collection-fetch">fetch</a></li>
<li>– <a href="#Collection-create">create</a></li>
</ul>
<a class="toc_title" href="#Sync">
Sync
</a>
<ul class="toc_section">
<li>– <a href="#Sync">Backbone.sync</a></li>
</ul>
<a class="toc_title" href="#View">
View
</a>
<ul class="toc_section">
<li>– <a href="#View-extend">extend</a></li>
<li>– <a href="#View-constructor">constructor / initialize</a></li>
<li>– <a href="#View-el">el</a></li>
<li>– <a href="#View-jQuery">$ (jQuery)</a></li>
<li>– <a href="#View-render">render</a></li>
<li>– <a href="#View-make">make</a></li>
<li>– <a href="#View-handleEvents">handleEvents</a></li>
</ul>
<a class="toc_title" href="#changelog">
Change Log
</a>
</div>
<div class="container">
<p>
<img style="width: 385px; height: 126px;" src="docs/images/backbone.png" alt="Backbone.js" />
</p>
<p>
<a href="http://github.com/documentcloud/backbone/">Backbone</a>
supplies structure to JavaScript-heavy applications by providing <b>models</b> with
key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions,
<b>views</b> with declarative event handling, and connects it all to your
existing application over a RESTful JSON interface.
</p>
<p>
The project is <a href="http://github.com/documentcloud/backbone/">hosted on GitHub</a>,
and the <a href="docs/backbone.html">annotated source code</a> is available,
as well as an online <a href="test/test.html">test suite</a>.
</p>
<p>
<i>
Backbone is an open-source component of
<a href="http://documentcloud.org/">DocumentCloud</a>.
</i>
</p>
<h2 id="downloads">
Downloads & Dependencies
<span style="padding-left: 7px; font-size:11px; font-weight: normal;" class="interface">(Right-click, and use "Save As")</span>
</h2>
<table>
<tr>
<td><a href="backbone.js">Development Version (0.1.0)</a></td>
<td><i>21kb, Uncompressed with Comments</i></td>
</tr>
<tr>
<td><a href="backbone-min.js">Production Version (0.1.0)</a></td>
<td><i>2kb, Packed and Gzipped</i></td>
</tr>
</table>
<p>
Backbone's only hard dependency is
<a href="http://documentcloud.github.com/underscore/">Underscore.js</a>.
For RESTful persistence, and DOM manipulation with
<a href="#View">Backbone.View</a>,
it's highly recommended to include <a href="http://jquery.com">jQuery</a>,
and <a href="http://www.json.org/json2.js">json2.js</a>
(both of which you may already have on the page).
</p>
<h2 id="Introduction">Introduction</h2>
<p>
When working on a web application that involved a lot of JavaScript, one
of the first things you learn is to stop tying your data to the DOM. It's all
too easy to create JavaScript applications that end up as tangled piles of
jQuery selectors and callbacks, all trying frantically to keep data in
sync between the HTML UI, your JavaScript logic, and the database on your
server. For rich client-side applications, a more structured approach
is helpful.
</p>
<p>
With Backbone, you represent your data as
<a href="#Model">Models</a>, which can be created, validated, destroyed,
and saved to the server. Whenever a UI action causes an attribute of
a model to change, the model triggers a <i>"change"</i> event; all
the <a href="#View">Views</a> that display the model's data are notified of the
event, causing them to re-render. You don't have to write the glue
code that looks into the DOM to find an element with a specific <i>id</i>,
and update the HTML manually
— when the model changes, the views simply update themselves.
</p>
<p>
<i>How is this different than
<a href="http://www.sproutcore.com/">SproutCore</a> or
<a href="http://cappuccino.org/">Cappuccino</a>?
</i>
</p>
<p>
This question is frequently asked, and all three projects apply general
<a href="http://en.wikipedia.org/wiki/Model–View–Controller">Model-View-Controller</a>
principles to JavaScript applications. However, there isn't much basis
for comparsion. SproutCore and Cappuccino provide rich UI widgets, vast
core libraries, and determine the structure of your HTML for you.
Both frameworks measure in the hundreds of kilobytes when packed and
gzipped, and megabytes of JavaScript, CSS, and images when loaded in the browser
— there's a lot of room underneath for libraries of a more moderate scope.
Backbone is a <i>2 kilobyte</i> include that provides
just the core concepts of models, events (key-value binding), collections,
views, and persistence. A much closer relative to Backbone is
<a href="http://benpickles.github.com/js-model/">js-model</a>.
</p>
<p>
Many of the examples that follow are runnable. Click the <i>play</i> button
to execute them.
</p>
<h2 id="Events">Backbone.Events</h2>
<p>
<b>Events</b> is a module that can be mixed in to any object, giving the
object the ability to bind and trigger custom named events. Events do not
have to be declared before they are bound, and may take passed arguments.
For example:
</p>
<pre class="runnable">
var object = {};
_.extend(object, Backbone.Events);
object.bind("alert", function(msg) {
alert("Triggered " + msg);
});
object.trigger("alert", "an event");
</pre>
<p id="Events-bind">
<b class="header">bind</b><code>object.bind(event, callback)</code>
<br />
Bind a <b>callback</b> function to an object. The callback will be invoked
whenever the <b>event</b> (specified by an arbitrary string identifier) is fired.
If you have a large number of different events on a page, the convention is to use colons to
namespace them: <tt>"poll:start"</tt>, or <tt>"change:selection"</tt>
</p>
<p>
Callbacks bound to the special
<tt>"all"</tt> event will be triggered when any event occurs, and are passed
the name of the event as the first argument. For example, to proxy all events
from one object to another:
</p>
<pre>
proxy.bind("all", function(eventName) {
object.trigger(eventName);
});
</pre>
<p id="Events-unbind">
<b class="header">unbind</b><code>object.unbind([event], [callback])</code>
<br />
Remove a previously-bound <b>callback</b> function from an object. If no
callback is specified, all callbacks for the <b>event</b> will be
removed. If no event is specified, <i>all</i> event callbacks on the object
will be removed.
</p>
<pre>
object.unbind("change", onChange); // Removes just the onChange callback.
object.unbind("change"); // Removes all "change" callbacks.
object.unbind(); // Removes all callbacks on object.
</pre>
<p id="Events-trigger">
<b class="header">trigger</b><code>object.trigger(event, [*args])</code>
<br />
Trigger callbacks for the given <b>event</b>. Subsequent arguments to
<b>trigger</b> will be passed along to the event callbacks.
</p>
<h2 id="Model">Backbone.Model</h2>
<p>
<b>Models</b> are the heart of any JavaScript application, containing
the interactive data as well as a large part of the logic surrounding it:
conversions, validations, computed properties, and access control. You
extend <b>Backbone.Model</b> with your domain-specific methods, and
<b>Model</b> provides a basic set of functionality for managing changes.
</p>
<p>
The following is a contrived example, but it demonstrates defining a model
with a custom method, setting an attribute, and firing an event keyed
to changes in that specific attribute.
After running this code once, <tt>sidebar</tt> will be
available in your browser's console, so you can play around with it.
</p>
<pre class="runnable">
var Sidebar = Backbone.Model.extend({
promptColor: function() {
var cssColor = prompt("Please enter a CSS color:");
this.set({color: cssColor});
}
});
window.sidebar = new Sidebar;
sidebar.bind('change:color', function(model, color) {
$('#sidebar').css({background: color});
});
sidebar.set({color: 'white'});
sidebar.promptColor();
</pre>
<p id="Model-extend">
<b class="header">extend</b><code>Backbone.Model.extend(properties, [classProperties])</code>
<br />
To create a <b>Model</b> class of your own, you extend <b>Backbone.Model</b>
and provide instance <b>properties</b>, as well as optional
<b>classProperties</b> to be attached directly to the constructor function.
</p>
<p>
<b>extend</b> correctly sets up the prototype chain, so subclasses created
with <b>extend</b> can be further extended and subclassed as far as you like.
</p>
<pre>
var Note = Backbone.Model.extend({
initialize: function() { ... },
author: function() { ... },
allowedToEdit: function(account) { ... },
coordinates: function() { ... }
});
</pre>
<p id="Model-constructor">
<b class="header">constructor / initialize</b><code>new Model([attributes])</code>
<br />
When creating an instance of a model, you can pass in the initial values
of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
model. If you define an <b>initialize</b> function, it will be invoked when
the model is created.
</p>
<pre>
new Book({
title: "One Thousand and One Nights",
author: "Scheherazade"
});
</pre>
<p id="Model-get">
<b class="header">get</b><code>model.get(attribute)</code>
<br />
Get the current value of an attribute from the model. For example:
<tt>note.get("title")</tt>
</p>
<p id="Model-set">
<b class="header">set</b><code>model.set(attributes, [options])</code>
<br />
Set a hash of attributes (one or many) on the model. If any of the attributes
change the models state, a <tt>"change"</tt> event will be fired, unless
<tt>{silent: true}</tt> is passed as an option.
</p>
<p>
If the model has a <a href="#Model-validate">validate</a> method,
it will be validated before the attributes are set, and no changes will
occur if the validation fails.
</p>
<pre>
note.set({title: "October 12", content: "Lorem Ipsum Dolor Sit Amet..."});
</pre>
<p id="Model-unset">
<b class="header">unset</b><code>model.unset(attribute, [options])</code>
<br />
Remove an attribute by deleting it from the internal attributes hash.
Fires a <tt>"change"</tt> event unless <tt>silent</tt> is passed as an option.
</p>
<p id="Model-id">
<b class="header">id</b><code>model.id</code>
<br />
A special property of models, the <b>id</b> is an arbitrary string
(integer id or UUID). If you set the <b>id</b> in the
attributes hash, it will be copied onto the model as a direct property.
Models can be retrieved by id from collections, and the id is used to generate
model URLs by default.
</p>
<p id="Model-cid">
<b class="header">cid</b><code>model.cid</code>
<br />
A special property of models, the <b>cid</b> or client id is a unique identifier
automatically assigned to all models when they're first created. Client ids
are handy when the model has not yet been saved to the server, and does not
yet have its eventual true <b>id</b>, but already needs to be visible in the UI.
Client ids take the form: <tt>c1, c2, c3 ...</tt>
</p>
<p id="Model-attributes">
<b class="header">attributes</b><code>model.attributes</code>
<br />
The <b>attributes</b> property is the internal hash containing the model's
state. Please use <a href="#Model-set">set</a> to update the attributes instead of modifying
them directly. If you'd like to retrieve and munge a copy of the model's
attributes, use <a href="#Model-toJSON">toJSON</a> instead.
</p>
<p id="Model-toJSON">
<b class="header">toJSON</b><code>model.toJSON()</code>
<br />
Return a copy of the model's <a href="#Model-attributes">attributes</a> for JSON stringification.
This can be used for persistence, serialization, or for augmentation before
being handed off to a view. The name of this method is a bit confusing, as
it doesn't actually return a JSON string — but I'm afraid that it's
the way that the <a href="https://developer.mozilla.org/en/JSON#toJSON()_method">JavaScript API for <b>JSON.stringify</b> works</a>.
</p>
<pre class="runnable">
var artist = new Backbone.Model({
firstName: "Wassily",
lastName: "Kandinsky"
});
artist.set({birthday: "December 16, 1866"});
alert(JSON.stringify(artist));
</pre>
<p id="Model-save">
<b class="header">save</b><code>model.save(attributes, [options])</code>
<br />
Save a model to your database (or alternative persistence layer),
by delegating to <a href="#Sync">Backbone.sync</a>. If the model has a <a href="#Model-validate">validate</a>
method, and validation fails, the model will not be saved. If the model
<a href="#Model-isNew">isNew</a>, the save will be a <tt>"create"</tt>
(HTTP <tt>POST</tt>), if the model already
exists on the server, the save will be an <tt>"update"</tt> (HTTP <tt>PUT</tt>). Accepts
<tt>success</tt> and <tt>error</tt> callbacks in the options hash, which
are passed <tt>(model, response)</tt> as arguments.
</p>
<p>
In the following example, notice how because the model has never been
saved previously, our overridden version of <tt>Backbone.sync</tt> receives a <tt>"create"</tt> request.
</p>
<pre class="runnable">
Backbone.sync = function(method, model) {
alert(method + ": " + JSON.stringify(model));
};
var book = new Backbone.Model({
title: "The Rough Riders",
author: "Theodore Roosevelt"
});
book.save();
</pre>
<p id="Model-destroy">
<b class="header">destroy</b><code>model.destroy([options])</code>
<br />
Destroys the model on the server by delegating an HTTP <tt>DELETE</tt>
request to <a href="#Sync">Backbone.sync</a>. Accepts
<tt>success</tt> and <tt>error</tt> callbacks in the options hash.
</p>
<pre>
book.destroy({success: function(model, response) {
...
}});
</pre>
<p id="Model-validate">
<b class="header">validate</b><code>model.validate(attributes)</code>
<br />
This method is left undefined, and you're encouraged to override it with
your custom validation logic, if you have any that can be performed
in JavaScript. <b>validate</b> is called before <tt>set</tt> and
<tt>save</tt>, and is passed the attributes that are about to be updated.
If the model and attributes are valid, don't return anything from <b>validate</b>;
if the attributes are invalid, return an error of your choosing. It
can be as simple as a string error message to be displayed, or a complete
error object that describes the error programmatically. <tt>set</tt> and
<tt>save</tt> will not continue if <b>validate</b> returns an error.
Failed validations trigger an <tt>"error"</tt> event.
</p>
<pre class="runnable">
var Chapter = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.end < attrs.start) {
return "can't end before it starts";
}
}
});
var one = new Chapter({
title : "Chapter One: The Beginning"
});
one.bind("error", function(model, error) {
alert(model.get("title") + " " + error);
});
one.set({
start: 15,
end: 10
});
</pre>
<p id="Model-url">
<b class="header">url</b><code>model.url()</code>
<br />
Returns the relative URL where the model's resource would be located on
the server. If your models are located somewhere else, override this method
with the correct logic. Generates URLs of the form: <tt>"/[collection]/[id]"</tt>.
</p>
<p>
A model with an id of <tt>101</tt>, stored in a
<a href="#Collection">Backbone.Collection</a> with a <tt>url</tt> of <tt>"/notes"</tt>,
would have this URL: <tt>"/notes/101"</tt>
</p>
<p id="Model-clone">
<b class="header">clone</b><code>model.clone()</code>
<br />
Returns a new instance of the model with identical attributes.
</p>
<p id="Model-isNew">
<b class="header">isNew</b><code>model.isNew()</code>
<br />
Has this model been saved to the server yet? If the model does not yet have
an <tt>id</tt>, it is considered to be new.
</p>
<p id="Model-change">
<b class="header">change</b><code>model.change()</code>
<br />
Manually trigger the <tt>"change"</tt> event.
If you've been passing <tt>{silent: true}</tt> to the <a href="#Model-set">set</a> function in order to
aggregate rapid changes to a model, you'll want to call <tt>model.change()</tt>
when you're all finished.
</p>
<p id="Model-hasChanged">
<b class="header">hasChanged</b><code>model.hasChanged([attribute])</code>
<br />
Has the model changed since the last <tt>"change"</tt> event? If an <b>attribute</b>
is passed, returns <tt>true</tt> if that specific attribute has changed.
</p>
<pre>
book.bind("change", function() {
if (book.hasChanged("title")) {
...
}
});
</pre>
<p id="Model-changedAttributes">
<b class="header">changedAttributes</b><code>model.changedAttributes([attributes])</code>
<br />
Retrieve a hash of only the model's attributes that have changed. Optionally,
an external <b>attributes</b> hash can be passed in, returning
the attributes in that hash which differ from the model. This can be used
to figure out which portions of a view should be updated, or what calls
need to be made to sync the changes to the server.
</p>
<p id="Model-previous">
<b class="header">previous</b><code>model.previous(attribute)</code>
<br />
During a <tt>"change"</tt> event, this method can be used to get the
previous value of a changed attribute.
</p>
<pre class="runnable">
var bill = new Backbone.Model({
name: "Bill Smith"
});
bill.bind("change:name", function(model, name) {
alert("Changed name from " + bill.previous("name") + " to " + name);
});
bill.set({name : "Bill Jones"});
</pre>
<p id="Model-previousAttributes">
<b class="header">previousAttributes</b><code>model.previousAttributes()</code>
<br />
Return a copy of the model's previous attributes. Useful for getting a
diff between versions of a model, or getting back to a valid state after
an error occurs.
</p>
<h2 id="Collection">Backbone.Collection</h2>
<p>
Collections are ordered sets of models. You can bind callbacks to be notified
when any model in the collection is changed, listen for <tt>"add"</tt> and
<tt>"remove"</tt> events, <tt>fetch</tt> the collection from the server,
and use a full suite of
<a href="#Collection-Underscore-Methods">Underscore.js methods</a>.
</p>
<p id="Collection-extend">
<b class="header">extend</b><code>Backbone.Collection.extend(properties, [classProperties])</code>
<br />
To create a <b>Collection</b> class of your own, extend <b>Backbone.Collection</b>,
providing instance <b>properties</b>, as well as optional <b>classProperties</b> to be attached
directly to the collection's constructor function.
</p>
<p id="Collection-constructor">
<b class="header">constructor / initialize</b><code>new Collection([models], [options])</code>
<br />
When creating a Collection, you may choose to pass in the initial array of <b>models</b>.
The collection's <a href="#Collection-comparator">comparator</a> function
may be included as an option. If you define an <b>initialize</b> function, it will be
invoked when the collection is created.
</p>
<pre>
var tabs = new TabSet([tab1, tab2, tab3]);
</pre>
<p id="Collection-models">
<b class="header">models</b><code>collection.models</code>
<br />
Raw access to the JavaScript array of models inside of the collection. Usually you'll
want to use <tt>get</tt>, <tt>at</tt>, or the <b>Underscore methods</b>
to access model objects, but occasionally a direct reference to the array
is desired.
</p>
<p id="Collection-Underscore-Methods">
<b class="header">Underscore Methods (24)</b>
<br />
Backbone proxies to <b>Underscore.js</b> to provide 24 iteration functions
on <b>Backbone.Collection</b>. They aren't all documented here, but
you can take a look at the Underscore documentation for the full details…
</p>
<ul>
<li><a href="http://documentcloud.github.com/underscore/#each">forEach (each)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#map">map</a></li>
<li><a href="http://documentcloud.github.com/underscore/#reduce">reduce (foldl, inject)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#reduceRight">reduceRight (foldr)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#detect">find (detect)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#select">filter (select)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#reject">reject</a></li>
<li><a href="http://documentcloud.github.com/underscore/#all">every (all)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#any">some (any)</a></li>
<li><a href="http://documentcloud.github.com/underscore/#include">include</a></li>
<li><a href="http://documentcloud.github.com/underscore/#invoke">invoke</a></li>
<li><a href="http://documentcloud.github.com/underscore/#max">max</a></li>
<li><a href="http://documentcloud.github.com/underscore/#min">min</a></li>
<li><a href="http://documentcloud.github.com/underscore/#sortBy">sortBy</a></li>
<li><a href="http://documentcloud.github.com/underscore/#sortedIndex">sortedIndex</a></li>
<li><a href="http://documentcloud.github.com/underscore/#toArray">toArray</a></li>
<li><a href="http://documentcloud.github.com/underscore/#size">size</a></li>
<li><a href="http://documentcloud.github.com/underscore/#first">first</a></li>
<li><a href="http://documentcloud.github.com/underscore/#rest">rest</a></li>
<li><a href="http://documentcloud.github.com/underscore/#last">last</a></li>
<li><a href="http://documentcloud.github.com/underscore/#without">without</a></li>
<li><a href="http://documentcloud.github.com/underscore/#indexOf">indexOf</a></li>
<li><a href="http://documentcloud.github.com/underscore/#lastIndexOf">lastIndexOf</a></li>
<li><a href="http://documentcloud.github.com/underscore/#isEmpty">isEmpty</a></li>
</ul>
<pre>
Books.each(function(book) {
book.publish();
});
var titles = Books.map(function(book) {
return book.get("title");
});
var publishedBooks = Books.filter(function(book) {
return book.get("published") === true;
});
var alphabetical = Books.sortBy(function(book) {
return book.author.get("name").toLowerCase();
});
</pre>
<p id="Collection-add">
<b class="header">add</b><code>collection.add(models, [options])</code>
<br />
Add a model (or an array of models) to the collection. Fires an <tt>"add"</tt>
event, which you can pass <tt>{silent: true}</tt> to suppress.
</p>
<pre class="runnable">
var Ship = Backbone.Model;
var ships = new Backbone.Collection;
ships.bind("add", function(ship) {
alert("Ahoy " + ship.get("name") + "!");
});
ships.add([
new Ship({name: "Flying Dutchman"}),
new Ship({name: "Black Pearl"})
]);
</pre>
<p id="Collection-remove">
<b class="header">remove</b><code>collection.remove(models, [options])</code>
<br />
Remove a model (or an array of models) from the collection. Fires a
<tt>"remove"</tt> event, which you can use <tt>silent</tt>
to suppress.
</p>
<p id="Collection-get">
<b class="header">get</b><code>collection.get(id)</code>
<br />
Get a model from a collection, specified by <b>id</b>.
</p>
<pre>
var book = Library.get(110);
</pre>
<p id="Collection-getByCid">
<b class="header">getByCid</b><code>collection.getByCid(cid)</code>
<br />
Get a model from a collection, specified by client id. The client id
is the <tt>.cid</tt> property of the model, automatically assigned whenever
a model is created. Useful for models which have not yet been saved to
the server, and do not yet have true ids.
</p>
<p id="Collection-at">
<b class="header">at</b><code>collection.at(index)</code>
<br />
Get a model from a collection, specified by index. Useful if your collection
is sorted, and if your collection isn't sorted, <b>at</b> will still
retrieve models in insertion order.
</p>
<p id="Collection-length">
<b class="header">length</b><code>collection.length</code>
<br />
Like an array, a Collection maintains a <tt>length</tt> property, counting
the number of models it contains.
</p>
<p id="Collection-comparator">
<b class="header">comparator</b><code>collection.comparator</code>
<br />
By default there is no <b>comparator</b> function on a collection.
If you define a comparator, it will be used to maintain
the collection in sorted order. This means that as models are added,
they are inserted at the correct index in <tt>collection.models</tt>.
Comparator functions take a model and return a numeric or string value
by which the model should be ordered relative to others.
</p>
<p>
Note how even though all of the chapters in this example are added backwards,
they come out in the proper order:
</p>
<pre class="runnable">
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = function(chapter) {
return chapter.get("page");
};
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
alert(chapters.pluck('title'));
</pre>
<p id="Collection-sort">
<b class="header">sort</b><code>collection.sort([options])</code>
<br />
Force a collection to re-sort itself. You don't need to call this under
normal circumstances, as a collection with a <a href="#Collection-comparator">comparator</a> function
will maintain itself in proper sort order at all times. Triggers the
collection's <tt>"refresh"</tt> event, unless silenced by passing
<tt>{silent: true}</tt>
</p>
<p id="Collection-pluck">
<b class="header">pluck</b><code>collection.pluck(attribute)</code>
<br />
Pluck an attribute from each model in the collection. Equivalent to calling
<tt>map</tt>, and returning a single attribute from the iterator.
</p>
<pre class="runnable">
var stooges = new Backbone.Collection([
new Backbone.Model({name: "Curly"}),
new Backbone.Model({name: "Larry"}),
new Backbone.Model({name: "Moe"})
]);
var names = stooges.pluck("name");
alert(JSON.stringify(names));
</pre>
<p id="Collection-url">
<b class="header">url</b><code>collection.url or collection.url()</code>
<br />
Set the <b>url</b> property (or function) on a collection to reference
its location on the server. Models within the collection will use <b>url</b>
to construct URLs of their own.
</p>
<pre>
var Notes = Backbone.Collection.extend({
url: '/notes'
});
// Or, something more sophisticated:
var Notes = Backbone.Collection.extend({
url: function() {
return this.document.url() + '/notes';
}
});
</pre>
<p id="Collection-refresh">
<b class="header">refresh</b><code>collection.refresh(models, [options])</code>
<br />
Adding and removing models one at a time is all well and good, but sometimes
you have so many models to change that you'd rather just update the collection
in bulk. Use <b>refresh</b> to replace a collection with a new list
of models (or attribute hashes), triggering a single <tt>"refresh"</tt> event
at the end. Pass <tt>{silent: true}</tt> to suppress the <tt>"refresh"</tt> event.
</p>
<p id="Collection-fetch">
<b class="header">fetch</b><code>collection.fetch([options])</code>
<br />
Fetch the default set of models for this collection from the server,
refreshing the collection when they arrive. The <b>options</b> hash takes
<tt>success</tt> and <tt>error</tt>
callbacks which will be passed <tt>(collection, response)</tt> as arguments.
Delegates to <a href="#Sync">Backbone.sync</a>
under the covers, for custom persistence strategies.
</p>
<p>
The server handler for <b>fetch</b> requests should return a JSON list of
models, namespaced under "models": <tt>{"models": [...]}</tt> —
additional information can be returned with the response under different keys.
</p>
<pre class="runnable">
Backbone.sync = function(method, model) {
alert(method + ": " + model.url);
};
var accounts = new Backbone.Collection;
accounts.url = '/accounts';
accounts.fetch();
</pre>
<p>
Note that <b>fetch</b> should not be used to populate collections on