forked from addyosmani/backbone-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-fundamentals.rtf
7540 lines (7539 loc) · 528 KB
/
backbone-fundamentals.rtf
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
{\rtf1\ansi\deff0{\fonttbl{\f0 \fswiss Helvetica;}{\f1 Courier;}}
{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}
\widowctrl\hyphauto
{\pard \qc \f0 \sa180 \li0 \fi0 \b \fs36 Developing Backbone.js Applications\par}
{\pard \qc \f0 \sa180 \li0 \fi0 Addy Osmani\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Prelude\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Welcome to my (in-progress) book about the {\field{\*\fldinst{HYPERLINK "http://documentcloud.github.com/backbone/"}}{\fldrslt{\ul
Backbone.js
}}}
framework for structuring JavaScript applications. It\u8217's released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported {\field{\*\fldinst{HYPERLINK "http://creativecommons.org/licenses/by-nc-sa/3.0/"}}{\fldrslt{\ul
license
}}}
meaning you can both grab a copy of the book for free or help to further {\field{\*\fldinst{HYPERLINK "https://github.com/addyosmani/backbone-fundamentals/"}}{\fldrslt{\ul
improve
}}}
it.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 I\u8217'm very pleased to announce that this book will be out in physical form later in the year via {\field{\*\fldinst{HYPERLINK "http://oreilly.com"}}{\fldrslt{\ul
O\u8217'Reilly Media
}}}
. Readers will have the option of purchasing the latest version in either print or a number of digital formats then or can grab a recent version from this repository.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help. My extended thanks go out to {\field{\*\fldinst{HYPERLINK "https://github.com/jashkenas"}}{\fldrslt{\ul
Jeremy Ashkenas
}}}
for creating Backbone.js and {\field{\*\fldinst{HYPERLINK "https://github.com/addyosmani/backbone-fundamentals/contributors"}}{\fldrslt{\ul
these
}}}
members of the community for their assistance tweaking this project.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 I hope you find this book helpful!\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Notes:}\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Items added or updated in the last month are marked with a * in the outline.\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Once you\u8217're familiar with Backbone.js, you might be interested in checking out {\field{\*\fldinst{HYPERLINK "https://github.com/addyosmani/aura"}}{\fldrslt{\ul
Aura
}}}
.\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Table Of Contents\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#introduction"}}{\fldrslt{\ul
Introduction
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab MVC, Or Rather MV* Frameworks\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab What is Backbone.js?\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab When Do You Need A JavaScript MV* Framework?\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab When To Consider Using Backbone.js\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#fundamentals"}}{\fldrslt{\ul
Fundamentals
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#mvc-mvp"}}{\fldrslt{\ul
MVC, MVP & Backbone.js
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#theinternals"}}{\fldrslt{\ul
The Internals
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-models"}}{\fldrslt{\ul
Models
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-views"}}{\fldrslt{\ul
Views
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-collections"}}{\fldrslt{\ul
Collections
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-events"}}{\fldrslt{\ul
Events
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-routers"}}{\fldrslt{\ul
Routers
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-inheritance"}}{\fldrslt{\ul
Inheritance & Mixins
}}}
*\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#thebasics-namespacing"}}{\fldrslt{\ul
Namespacing
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#practicaltodos"}}{\fldrslt{\ul
Practical: Todos - Your First Backbone.js App
}}}
*\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#backboneboilerplate"}}{\fldrslt{\ul
Backbone Boilerplate & Grunt BBB
}}}
*\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#commonproblems"}}{\fldrslt{\ul
Common Problems & Solutions
}}}
*\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Sub-Views And Nesting\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Managing Models In Nested Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Views Triggering Other Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Child Views Rendering Parent Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Cleanly Disposing Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Disposing Parent And Child Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Appending Views\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Better Model Property Validation *\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#advanced"}}{\fldrslt{\ul
Modular Development
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#modularjs"}}{\fldrslt{\ul
Introduction
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#organizingmodules"}}{\fldrslt{\ul
Organizing modules with RequireJS and AMD
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#externaltemplates"}}{\fldrslt{\ul
Keeping your templates external
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#practicalrequirejs"}}{\fldrslt{\ul
Practical: A Modular App Using AMD & RequireJS
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#optimizingrequirejs"}}{\fldrslt{\ul
Optimize Apps With The RequireJS Optimizer
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#optimizebuild"}}{\fldrslt{\ul
Optimize Apps With RequireJS Using Packages
}}}
*\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#decouplingbackbone"}}{\fldrslt{\ul
Decoupling Backbone With The Mediator And Facade Patterns
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 Backbone.js Extensions\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#marionette"}}{\fldrslt{\ul
Backbone Marionette
}}}
*\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#restfulapps"}}{\fldrslt{\ul
RESTful Applications With Backbone.js
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#restful"}}{\fldrslt{\ul
Building RESTful applications
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#stack1"}}{\fldrslt{\ul
Apps With Node.js, Express, Mongoose and MongoDB
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#stack2"}}{\fldrslt{\ul
Apps with Ruby, Sinatra, Haml and MongoDB
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#pagination"}}{\fldrslt{\ul
Paginating Backbone.js Requests & Collections
}}}
*\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 Mobile Applications\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Backbone & jQuery Mobile\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Practical: Building A Modular Mobile App With Backbone & jQuery Mobile\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#testing"}}{\fldrslt{\ul
Unit Testing
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#unittestingjasmine"}}{\fldrslt{\ul
Unit Testing Backbone Applications With Jasmine
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Introduction\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Jasmine\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Suites, Specs And Spies\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab TDD With Backbone\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Models\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Collections\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Views\sa180\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#unittestingqunit"}}{\fldrslt{\ul
Unit Testing Backbone Applications With QUnit And SinonJS
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Introduction\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab QUnit\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Assertions\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Adding structure to assertions\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Assertion examples\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Fixtures\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Asynchronous code\sa180\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab SinonJS\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Stubs\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Mocks\sa180\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab Practical\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Models\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Collections\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Views\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab Testing Events\sa180\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#resources"}}{\fldrslt{\ul
Resources
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Introduction\par}
{\pard \ql \f0 \sa180 \li0 \fi0 When writing a Web application from scratch, it\u8217's easy to feel like we can get by simply by relying on a DOM manipulation library (like jQuery) and a handful of utility plugins. The problem with this is that it doesn\u8217't take long to get lost in a nested pile of jQuery callbacks and DOM elements without any real structure in place for our applications.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In short, we\u8217're stuck with spaghetti code. Fortunately there are modern JavaScript frameworks that can assist with bringing structure and organization to our projects, improving how easily maintainable they are in the long-run.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 What Is MVC, Or Rather MV*?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 These modern frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application down into three parts:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Models represent the domain-specific knowledge and data in an application. Think of this as being a \u8216'type\u8217' of data you can model \u8212- like a User, Photo or Note. Models should notify anyone observing them about their current state (e.g Views).\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Views are typically considered the User-interface in an application (e.g your markup and templates), but don\u8217't have to be. They should know about the existence of Models in order to observe them, but don\u8217't directly communicate with them.\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Controllers handle the input (e.g clicks, user actions) in an application and Views can be considered as handling the output. When a Controller updates the state of a model (such as editing the caption on a Photo), it doesn\u8217't directly tell the View. This is what the observing nature of the View and Model relationship is for.\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 JavaScript \u8216'MVC\u8217' frameworks that can help us structure our code don\u8217't always strictly follow the above pattern. Some frameworks will include the responsibility of the Controller in the View (e.g Backbone.js) whilst others add their own opinionated components into the mix as they feel this is more effective.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 For this reason we refer to such frameworks as following the MV* pattern, that is, you\u8217're likely to have a View and a Model, but more likely to have something else also included.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 What exactly is Backbone.js?\par}
{\pard \ql \f0 \sa0 \li0 \fi0 \par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone.js is a lightweight JavaScript framework for adding structure to your client-side code. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Developers commonly use frameworks like Backbone.js to create single-page applications or SPAs. To put it simply, these apps enable the browser to react to changes in data on the client-side without the need to completely load up all your markup from the server, meaning no complete page-refreshes are necessary.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone.js is a mature, popular framework at the time of writing and has both a large development community online as well as a wealth of plugins and extensions available to build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and Foursquare.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 When Do You Need A JavaScript MV* Framework?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 When building a single-page application using JavaScript, whether it involves a complex user interface or is simply trying to reduce the number of HTTP requests required for new Views, you will likely find yourself inventing many of the pieces that make up an MV* framework like Backbone or Ember.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 At the outset, it isn\u8217't terribly difficult to write an application framework that offers some opinionated way to avoid spaghetti code, however to say that it is equally as trivial to write something of the standard of Backbone would be a grossly incorrect assumption.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There\u8217's a lot more that goes into structuring an application than tying together a DOM manipulation library, templating and routing. Mature MV* frameworks typically not only include many of the pieces you would find yourself writing, but also include solutions to problems you\u8217'll find yourself running into later on down the road. This is a time-saver that you shouldn\u8217't underestimate the value of.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 So, where will you likely need an MV* framework and where won\u8217't you?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If you\u8217're writing an application that will likely only be communicating with an API or back-end data service, where much of the heavy lifting for viewing or manipulating that data will be occurring in the browser, you may find a JavaScript MV* framework useful. Good examples of applications that fall into this category are GMail and Google Docs.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 These applications typically download a single payload containing all the scripts, stylesheets and markup users need for common tasks and then perform a lot of additional behavior in the background. It\u8217's trivial to switch between reading an email or document to writing one and you don\u8217't need to ask the application to render the whole page again at all.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If, however, you\u8217're building an application that still relies on the server for most of the heavy-lifting of Views/pages and you\u8217're just using a little JavaScript or jQuery to make things a little more interactive, an MV framework may be overkill. There certainly are complex Web applications where the partial rendering of views can* be coupled with a single-page application effectively, but for everything else, you may find yourself better sticking to a simpler setup.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Maturity in software (framework) development isn\u8217't simply about how long a framework has been around. It\u8217's about how solid the framework is and more importantly how well it\u8217's evolved to fill its role. Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Why should you consider using Backbone.js?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Does the following describe you?:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 "I want something flexible which offers a minimalist solution to separating concerns in my application. It should support a persistence layer and RESTful sync, models, views (with controllers), event-driven communication, templating and routing. It should be imperative, allowing one to update the View when a model changes. I\u8217'd like some decisions about the architecture left up to me. Ideally, many large companies have used the solution to build non-trivial applications.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As I may be building something complex, I\u8217'd like there to be an active extension community around the framework that have already tried addressing larger problems (Marionette, Chaplin, Aura, Thorax). Ideally, there are also scaffolding tools (grunt-bbb, brunch) available for the solution."\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If so, continue reading.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone\u8217's main benefits, regardless of your target platform or device, include helping:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Organize the structure to your application\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Simplify server-side persistence\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Decouple the DOM from your page\u8217's data\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Model data, views and routers in a succinct manner\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Provide DOM, model and collection synchronization\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 What should you expect to see in this book?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The goal of this book is to create an authoritative and centralized repository of information that can help those developing real-world apps with Backbone. If you come across a section or topic which you think could be improved or expanded on, please feel free to submit a pull-request. It won\u8217't take long and you\u8217'll be helping other developers avoid problems you\u8217've run into before.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Topics will include MVC theory and how to build applications using Backbone\u8217's models, views, collections and routers. I\u8217'll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), how to build applications using modern software stacks (like Node and Express), how to solve the routing problems with Backbone and jQuery Mobile, tips about scaffolding tools, and a lot more.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Fundamentals\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section, we\u8217're going to explore how frameworks like Backbone.js fit in the world of JavaScript application architecture. Classically, developers creating desktop and server-class applications have had a wealth of design patterns available for them to lean on, but it\u8217's only been in the past few years that such patterns have come to client-side development.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 MVC, MVP & Backbone.js\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Design patterns are proven solutions to common development problems and can suggest structural approaches to help guide developers in adding some organization to their applications.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Patterns are useful because they\u8217're a set of practices that build upon the collective experience of skilled developers who have repeatedly solved similar problems. Although developers 10 or 20 years ago may not have been using the same programming languages when implementing patterns in their projects, there are many lessons we can learn from their efforts.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section, we\u8217're going to review two popular patterns - MVC and MVP. We\u8217'll be exploring in greater detail how Backbone.js implements these patterns shortly to better appreciate where it fits in.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 MVC\par}
{\pard \ql \f0 \sa180 \li0 \fi0 MVC (Model-View-Controller) is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally present to manage logic, user-input and the coordination of models and views. The pattern was originally designed by {\field{\*\fldinst{HYPERLINK "http://en.wikipedia.org/wiki/Trygve_Reenskaug"}}{\fldrslt{\ul
Trygve Reenskaug
}}}
while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in {\field{\*\fldinst{HYPERLINK "http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612"}}{\fldrslt{\ul
\u8220"Design Patterns: Elements of Reusable Object-Oriented Software\u8221"
}}}
(The \u8220"GoF\u8221" or \u8220"Gang of Four\u8221" book) in 1994, which played a role in popularizing its use.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Smalltalk-80 MVC\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It\u8217's important to understand what the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70\u8217's, graphical user-interfaces were few and far between. An approach known as {\field{\*\fldinst{HYPERLINK "http://martinfowler.com/eaaDev/uiArchs.html"}}{\fldrslt{\ul
Separated Presentation
}}}
began to be used as a means to make a clear division between domain objects which modeled concepts in the real world (e.g a photo, a person) and the presentation objects which were rendered to the user\u8217's screen.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The Smalltalk-80 implementation of MVC took this concept further and had an objective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of models for other interfaces in the application. There are some interesting points worth noting about Smalltalk-80\u8217's MVC architecture:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers)\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Presentation was taken care of by the View and the Controller, but there wasn\u8217't just a single view and controller. A View-Controller pair was required for each element being displayed on the screen and so there was no true separation between them\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab The Controller\u8217's role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab The Observer pattern was relied upon for updating the View whenever the Model changed\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Developers are sometimes surprised when they learn that the Observer pattern (nowadays commonly implemented as a Publish/Subscribe system) was included as a part of MVC\u8217's architecture decades ago. In Smalltalk-80\u8217's MVC, the View and Controller both observe the Model: anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - for the application to show real-time information, any change to the data in its Models should result in the View being refreshed instantly.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Martin Fowler has done an excellent job of writing about the {\field{\*\fldinst{HYPERLINK "http://martinfowler.com/eaaDev/uiArchs.html"}}{\fldrslt{\ul
origins
}}}
of MVC over the years and if you are interested in further historical information about Smalltalk-80\u8217's MVC, I recommend reading his work.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 MVC As We Know It\par}
{\pard \ql \f0 \sa180 \li0 \fi0 We\u8217've reviewed the 70\u8217's, but let us now return to the here and now. The MVC pattern has been applied to a diverse range of programming languages. For example, the popular Ruby on Rails is an implementation of a web application framework based on MVC for the Ruby language. JavaScript now has a number of MVC frameworks, including Ember.js, JavaScriptMVC, and of course Backbone.js. Given the importance of avoiding \u8220"spaghetti\u8221" code, a term which describes code that is very difficult to read or maintain due to its lack of structure, let\u8217's look at what the MVC pattern enables the Javascript developer to do.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 MVC is composed of three core components:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Models\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Models manage the data for an application. They are concerned with neither the user-interface nor presentation layers, but instead represent structured data that an application may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has occurred so that they may react accordingly.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 To understand models better, let us imagine we have a JavaScript photo gallery application. In a photo gallery, a photo would merit its own model, as it represents a unique kind of domain-specific data. The Photo model may represent attributes such as a caption, image source and additional meta-data. A specific photo would be stored in an instance of a model. Here\u8217's an example of a simple Photo model implemented with Backbone.js:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
\line
// Default attributes for the photo\line
defaults: \{\line
// Ensure that each photo created has an `src`.\line
src: "placeholder.jpg",\line
caption: "A default image",\line
viewed: false\line
\},\line
\line
initialize: function() \{\line
\}\line
\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The built-in capabilities of models vary across frameworks, however it\u8217's common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also need a way of persisting models. Persistence allows us to edit and update models with the knowledge that their most recent states will be saved somewhere, for example in a web browser\u8217's localStorage data-store or synchronized with a database.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 A model may also have multiple views observing it. Imagine our Photo model contained meta-data such as the longitude and latitude where the photo was taken, a list of people present in the photo, and a list of tags. A developer could create a single view that displayed all these attributes, or might create three separate views to display each attribute. The important detail is that the Photo model doesn\u8217't care how these views are organized, it simply announces updates to its data as necessary. We\u8217'll come back to Views in more detail later.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together. In Backbone, these groups are called \u8220"Collections\u8221". Managing models in groups allows us to write application logic based on notifications from the group, should any model it contains change. This avoids the need to manually observe individual model instances.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Here\u8217's how we might group Photo models into a simplified Backbone Collection:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoGallery = Backbone.Collection.extend(\{\line
\line
// Reference to this collection's model.\line
model: Photo,\line
\line
// Filter down the list of all photos that have been viewed\line
viewed: function() \{\line
return this.filter(function(photo)\{ return photo.get('viewed'); \});\line
\},\line
\line
// Filter down the list to only photos that have not yet been viewed\line
unviewed: function() \{\line
return this.without.apply(this, this.viewed());\line
\}\line
\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If you read older texts on MVC, you may come across a description of models as also managing application \u8216'state\u8217'. In JavaScript applications \u8220"state\u8221" has a specific meaning, typically referring to the current \u8220"state\u8221" of a view or sub-view on a user\u8217's screen at a fixed time. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Views\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, allowing the view to update itself accordingly. Design pattern literature commonly refers to views as \u8216'dumb\u8217', given that their knowledge of models and controllers in an application is limited.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Users interact with views, which usually means reading and editing model data. For example, in our photo gallery application example, model viewing might happen in a user interface with a big image, a caption, and a list of tags. Model editing could be done through an \u8220"edit\u8221" view where a user who has selected a specific photo could edit its caption, tags, or other metadata in a form.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In MVC, the actual task of updating the Model falls to Controllers, which we\u8217'll be covering shortly.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Let\u8217's explore Views a little further using a simple JavaScript example. Below we can see a function that creates a single Photo view, consuming both a model instance and a controller instance.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 We define a {\f1 render()} utility within our view which is responsible for rendering the contents of the {\f1 photoModel} using a JavaScript templating engine ({\field{\*\fldinst{HYPERLINK "http://underscorejs.org"}}{\fldrslt{\ul
Underscore
}}}
templating) and updating the contents of our view, referenced by {\f1 photoEl}.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The {\f1 photoModel} then adds our {\f1 render()} callback as one of its subscribers, so that through the Observer pattern it can trigger the view to update when the model changes.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 You may wonder where user interaction comes into play here. When users click on any elements within the view, it\u8217's not the view\u8217's responsibility to know what to do next. A Controller makes this decision. In our sample implementation, this is achieved by adding an event listener to {\f1 photoEl} which will delegate handling the click behavior back to the controller, passing the model information along with it in case it\u8217's needed.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The benefit of this architecture is that each component plays its own separate role in making the application function as needed.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var buildPhotoView = function( photoModel, photoController )\{\line
\line
var base = document.createElement('div'),\line
photoEl = document.createElement('div');\line
\line
base.appendChild(photoEl);\line
\line
var render= function()\{\line
// We use a templating library such as Underscore\line
// templating which generates the HTML for our\line
// photo entry\line
photoEl.innerHTML = _.template('photoTemplate', \{src: photoModel.getSrc()\});\line
\}\line
\line
photoModel.addSubscriber( render );\line
\line
photoEl.addEventListener('click', function()\{\line
photoController.handleEvent('click', photoModel );\line
\});\line
\line
var show = function()\{\line
photoEl.style.display = '';\line
\}\line
\line
var hide = function()\{\line
photoEl.style.display = 'none';\line
\}\line
\line
\line
return\{\line
showView: show,\line
hideView: hide\line
\}\line
\line
\}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Templating}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In the context of JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It has long been considered bad practice (and computationally expensive) to manually create large blocks of HTML markup in-memory through string concatenation. Developers using this technique often find themselves iterating through their data, wrapping it in nested divs and using outdated techniques such as {\f1 document.write} to inject the \u8216'template\u8217' into the DOM. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 JavaScript templating libraries (such as Handlebars.js or Mustache) are often used to define templates for views as HTML markup containing template variables. These template blocks can be either stored externally or within script tags with a custom type (e.g \u8216'text/template\u8217'). Variables are delimited using a variable syntax (e.g \{\{name\}\}). Javascript template libraries typically accept data in JSON, and the grunt work of populating templates with data is taken care of by the framework itself. This has a several benefits, particularly when opting to store templates externally as this can let applications load templates dynamically on an as-needed basis.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Let\u8217's compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore\u8217's \u8216'microtemplates\u8217'.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Handlebars.js:}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 <li class="photo">\line
<h2>\{\{caption\}\}</h2>\line
<img class="source" src="\{\{src\}\}"/>\line
<div class="meta-data">\line
\{\{metadata\}\}\line
</div>\line
</li>\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Underscore.js Microtemplates:}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 <li class="photo">\line
<h2><%= caption %></h2>\line
<img class="source" src="<%= src %>"/>\line
<div class="meta-data">\line
<%= metadata %>\line
</div>\line
</li>\par}
{\pard \ql \f0 \sa180 \li0 \fi0 You may also use double curly brackets (i.e {\f1 \{\{\}\}}) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore {\f1 templateSettings} attribute as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 _.templateSettings = \{ interpolate : /\\\{\\\{(.+?)\\\}\\\}/g \};\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b A note on navigation and state}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. Since this doesn\u8217't automatically update the URL, the role of navigation thus falls to a \u8220"router\u8221", which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Controllers\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Controllers are an intermediary between models and views which are classically responsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In our photo gallery application, a controller would be responsible for handling changes the user made to the edit view for a particular photo, updating a specific photo model when a user has finished editing.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It\u8217's with controllers that most JavaScript MVC frameworks depart from this interpretation of the MVC pattern. The reasons for this vary, but in my opinion, Javascript framework authors likely initially looked at server-side interpretations of MVC (such as Ruby on Rails), realized that that approach didn\u8217't translate 1:1 on the client-side, and so re-interpreted the C in MVC to solve their state management problem. This was a clever approach, but it can make it hard for developers coming to MVC for the first time to understand both the classical MVC pattern and the \u8220"proper\u8221" role of controllers in other non-Javascript frameworks.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 So does Backbone.js have Controllers? Not really. Backbone\u8217's Views typically contain \u8220"controller\u8221" logic, and Routers (discussed below) are used to help manage application state, but neither are true Controllers according to classical MVC.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It\u8217's in fact better to see it a member of the MV* family which approaches architecture in its own way. There is of course nothing wrong with this, but it is important to distinguish between classical MVC and MV* should you be relying on discussions of MVC to help with your Backbone projects.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Controllers in Spine.js vs Backbone.js\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Spine.js}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). Since Backbone doesn\u8217't have its {\b own} explicit controllers, it\u8217's useful to review the controller from another MVC framework to appreciate the difference in implementations. Let\u8217's take a look at {\field{\*\fldinst{HYPERLINK "http://spinejs.com/"}}{\fldrslt{\ul
Spine.js
}}}
:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this example, we\u8217're going to have a controller called {\f1 PhotosController} which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user edited the photo meta-data) the corresponding model does too.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 (Note: We won\u8217't be delving heavily into Spine.js beyond this example, but it\u8217's worth looking at it to learn more about Javascript frameworks in general.)\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 // Controllers in Spine are created by inheriting from Spine.Controller\line
\line
var PhotosController = Spine.Controller.sub(\{\line
init: function()\{\line
this.item.bind("update", this.proxy(this.render));\line
this.item.bind("destroy", this.proxy(this.remove));\line
\},\line
\line
render: function()\{\line
// Handle templating\line
this.replace($("#photoTemplate").tmpl(this.item));\line
return this;\line
\},\line
\line
remove: function()\{\line
this.$el.remove();\line
this.release();\line
\}\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller).\par}
{\pard \ql \f0 \sa180 \li0 \fi0 What we\u8217're doing in the above example is setting up listeners in the {\f1 update} and {\f1 destroy} events using {\f1 render()} and {\f1 remove()}. When a photo entry gets updated, we re-render the view to reflect the changes to the meta-data. Similarly, if the photo gets deleted from the gallery, we remove it from the view. In case you were wondering about the {\f1 tmpl()} function in the code snippet: in the {\f1 render()} function, we\u8217're using this to render a JavaScript template called #photoTemplate which simply returns an HTML string used to replace the controller\u8217's current element.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 What this provides us with is a very lightweight, simple way to manage changes between the model and the view.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Backbone.js}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Later on in this section we\u8217're going to revisit the differences between Backbone and traditional MVC, but for now let\u8217's focus on controllers.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In Backbone, controller logic is shared between Backbone.View and Backbone.Router. Earlier releases of Backbone contained something called Backbone.Controller, but it was renamed to Router to clarify its role.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 A Router\u8217's main purpose is to translate URL requests into application states. When a user browses to the URL www.example.com/photos/42, a Router could be used to show the photo with that ID, and to define what application behavior should be run in response to that request. Routers {\i can} contain traditional controller responsibilities, such as binding the events between models and views, or rendering parts of the page. However, Backbone contributor Tim Branyen has pointed out that it\u8217's possible to get away without needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoRouter = Backbone.Router.extend(\{\line
routes: \{ "photos/:id": "route" \},\line
\line
route: function(id) \{\line
var item = photoCollection.get(id);\line
var view = new PhotoView(\{ model: item \});\line
\line
something.html( view.render().el );\line
\}\line
\}):\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 What does MVC give us?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 To summarize, the separation of concerns in MVC facilitates modularization of an application\u8217's functionality and enables:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Easier overall maintenance. When updates need to be made to the application it is clear whether the changes are data-centric, meaning changes to models and possibly controllers, or merely visual, meaning changes to views.\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Decoupling models and views means that it\u8217's straight-forward to write unit tests for business logic\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Duplication of low-level model and controller code is eliminated across the application\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user-interfaces to work simultaneously\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Delving deeper\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we\u8217'll explore it a little further.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a \u8220"set of classes to build a user interface\u8221". In their view, it\u8217's actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I\u8217've covered some of these patterns in my other free book, JavaScript Design Patterns For Beginners if you would like to read into them further.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As we\u8217've discussed, models represent application data, while views handle what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core communication (something that surprisingly isn\u8217't covered in many articles about the MVC pattern). When a model is changed it \u8220"publishes\u8221" to the rest of the application that it has been updated. The \u8220"subscriber\u8221"\u8211-generally a Controller\u8211-then updates the view accordingly. The observer-viewer nature of this relationship is what facilitates multiple views being attached to the same model.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 For developers interested in knowing more about the decoupled nature of MVC (once again, depending on the implementation), one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different relationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Summary\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it\u8217's opted to approach Models, Views, Controllers or other alternatives, as this can better help you grok how the framework expects to be used.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 MVP\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named {\field{\*\fldinst{HYPERLINK "http://en.wikipedia.org/wiki/Taligent"}}{\fldrslt{\ul
Taligent
}}}
in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple components, there are some fundamental differences between them.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Models, Views & Presenters\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The P in MVP stands for presenter. It\u8217's a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes \u8220"dumb\u8221"), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other. They effectively bind models to views, a responsibility held by Controllers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it\u8217's the presenter\u8217's role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The benefit of this change from MVC is that it increases the testability of your application and provides a more clean separation between the view and the model. This isn\u8217't however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Although a common implementation of a {\field{\*\fldinst{HYPERLINK "http://martinfowler.com/eaaDev/PassiveScreen.html"}}{\fldrslt{\ul
Passive View
}}}
is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don\u8217't have the interface construct in JavaScript, we\u8217're using it more and more a protocol than an explicit interface here. It\u8217's technically still an API and it\u8217's probably fair for us to refer to it as an interface from that perspective.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There is also a {\field{\*\fldinst{HYPERLINK "http://martinfowler.com/eaaDev/SupervisingPresenter.html"}}{\fldrslt{\ul
Supervising Controller
}}}
variation of MVP, which is closer to the MVC and {\field{\*\fldinst{HYPERLINK "http://en.wikipedia.org/wiki/Model_View_ViewModel"}}{\fldrslt{\ul
MVVM
}}}
patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey\u8217's Backbone.ModelBinding plugin) introduce this idea of a Supervising Controller to Backbone.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 MVP or MVC?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 MVP is generally used most often in enterprise-level applications where it\u8217's necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn\u8217't quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Depending on the implementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other components. In my experience this really depends on the languages you are implementing MVP in (there\u8217's quite a difference between opting for MVP for a JavaScript project over one for say, ASP.NET).\par}
{\pard \ql \f0 \sa180 \li0 \fi0 At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 MVC, MVP and Backbone.js\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVP patterns in their classical form as many JavaScript developers don\u8217't view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.NET or GWT). This is because it\u8217's possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone contributor {\field{\*\fldinst{HYPERLINK "http://ireneros.com/"}}{\fldrslt{\ul
Irene Ros
}}}
subscribes to this way of thinking as when she separates Backbone views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a {\f1 Backbone.Router}, covered later in the book) or a callback in response to data being fetched.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab The presenter in MVP better describes the {\f1 Backbone.View} (the layer between View templates and the data bound to it) than a controller does\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab The model fits {\f1 Backbone.Model} (it isn\u8217't that different from the classical MVC \u8220"Model\u8221")\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab The views best represent templates (e.g Handlebars/Mustache markup templates)\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by {\f1 Backbone.View} because they\u8217're able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 We\u8217've also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Here, our Backbone {\f1 PhotoView} uses the Observer pattern to \u8216'subscribe\u8217' to changes to a View\u8217's model in the line {\f1 this.model.on('change',...)}. It also handles templating in the {\f1 render()} method, but unlike some other implementations, user interaction is also handled in the View (see {\f1 events}).\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoView = Backbone.View.extend(\{\line
\line
//... is a list tag.\line
tagName: "li",\line
\line
// Pass the contents of the photo template through a templating\line
// function, cache it for a single photo\line
template: _.template($('#photo-template').html()),\line
\line
// The DOM events specific to an item.\line
events: \{\line
"click img" : "toggleViewed"\line
\},\line
\line
// The PhotoView listens for changes to its model, re-rendering. Since there's\line
// a one-to-one correspondence between a **Photo** and a **PhotoView** in this\line
// app, we set a direct reference on the model for convenience.\line
\line
initialize: function() \{\line
_.bindAll(this, 'render');\line
this.model.on('change', this.render);\line
this.model.on('destroy', this.remove);\line
\},\line
\line
// Re-render the photo entry\line
render: function() \{\line
this.$el.html(this.template(this.model.toJSON()));\line
return this;\line
\},\line
\line
// Toggle the `"viewed"` state of the model.\line
toggleViewed: function() \{\line
this.model.viewed();\line
\}\line
\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Another (quite different) opinion is that Backbone more closely resembles {\field{\*\fldinst{HYPERLINK "http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController"}}{\fldrslt{\ul
Smalltalk-80 MVC
}}}
, which we went through earlier.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As regular Backbone user Derick Bailey has {\field{\*\fldinst{HYPERLINK "http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/"}}{\fldrslt{\ul
written
}}}
, it\u8217's ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone doesn\u8217't fit either MVC nor MVP perfectly. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well. Call it {\b the Backbone way}, MV* or whatever helps reference its flavor of application architecture.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It {\i is} however worth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Fast facts\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Backbone.js\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Core components: Model, View, Collection, Router. Enforces its own flavor of MV*\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Good documentation, with more improvements on the way\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Used by large companies such as SoundCloud and Foursquare to build non-trivial applications\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Event-driven communication between views and models. As we\u8217'll see, it\u8217's relatively straight-forward to add event listeners to any attribute in a model, giving developers fine-grained control over what changes in the view\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Supports data bindings through manual events or a separate Key-value observing (KVO) library\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Great support for RESTful interfaces out of the box, so models can be easily tied to a backend\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Extensive eventing system. It\u8217's {\field{\*\fldinst{HYPERLINK "http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/"}}{\fldrslt{\ul
trivial
}}}
to add support for pub/sub in Backbone\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Prototypes are instantiated with the {\f1 new} keyword, which some developers prefer\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Agnostic about templating frameworks, however Underscore\u8217's micro-templating is available by default. Backbone works well with libraries like Handlebars\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Doesn\u8217't support deeply nested models, though there are Backbone plugins such as {\field{\*\fldinst{HYPERLINK "https://github.com/PaulUithol/Backbone-relational"}}{\fldrslt{\ul
this
}}}
which can help\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Clear and flexible conventions for structuring applications. Backbone doesn\u8217't force usage of all of its components and can work with only those needed.\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 The Internals\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section, you\u8217'll learn the essentials of Backbone\u8217's models, views, collections and routers, as well as about using namespacing to organize your code. This isn\u8217't meant as a replacement for the official documentation, but it will help you understand many of the core concepts behind Backbone before you start building applications with it.\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Models\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Collections\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Routers\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Views\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Namespacing\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Models\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone models contain interactive data for an application as well as the logic around this data. For example, we can use a model to represent the concept of a photo object including its attributes like tags, titles and a location.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Models can be created by extending {\f1 Backbone.Model} as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
defaults: \{\line
src: 'placeholder.jpg',\line
title: 'an image placeholder',\line
coordinates: [0,0]\line
\},\line
initialize: function()\{\line
this.on("change:src", function()\{\line
var src = this.get("src");\line
console.log('Image source updated to ' + src);\line
\});\line
\},\line
changeSrc: function( source )\{\line
this.set(\{ src: source \});\line
\}\line
\});\line
\line
var somePhoto = new Photo(\{ src: "test.jpg", title:"testing"\});\line
somePhoto.changeSrc("magic.jpg"); // which triggers "change:src" and logs an update message to the console.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Initialization\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The {\f1 initialize()} method is called when a new instance of a model is created. Its use is optional, however you\u8217'll see why it\u8217's good practice to use it below.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
initialize: function()\{\line
console.log('this model has been initialized');\line
\}\line
\});\line
\line
// We can then create our own instance of a photo as follows:\line
var myPhoto = new Photo();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Getters & Setters\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Model.get()}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 Model.get()} provides easy access to a model\u8217's attributes. Attributes which are passed through to the model on instantiation are instantly available for retrieval.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myPhoto = new Photo(\{ title: "My awesome photo",\line
src:"boston.jpg",\line
location: "Boston",\line
tags:['the big game', 'vacation']\}),\line
\line
title = myPhoto.get("title"), //My awesome photo\line
location = myPhoto.get("location"), //Boston\line
tags = myPhoto.get("tags"), // ['the big game','vacation']\line
photoSrc = myPhoto.get("src"); //boston.jpg\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Alternatively, if you wish to directly access all of the attributes in a model\u8217's instance directly, you can achieve this as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myAttributes = myPhoto.attributes;\line
console.log(myAttributes);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It is best practice to use {\f1 Model.set()} or direct instantiation to set the values of a model\u8217's attributes.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Accessing {\f1 Model.attributes} directly is generally discouraged. Instead, should you need to read or clone data, {\f1 Model.toJSON()} is recommended for this purpose. If you would like to access or copy a model\u8217's attributes for purposes such as JSON stringification (e.g.\u160?for serialization prior to being passed to a view), this can be achieved using Model.toJSON(). Remember that this will return an object and JSON.stringify() should be used to get a string representation of the data:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myAttributes = myPhoto.toJSON();\line
console.log(JSON.stringify(myattributes));\line
/* this returns:\line
\{ title: "My awesome photo",\line
src:"boston.jpg",\line
location: "Boston",\line
tags:['the big game', 'vacation']\}\line
*/\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Model.set()\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 Model.set()} allows us to pass attributes into an instance of our model. Attributes can either be set during initialization or at any time afterwards. It\u8217's important to avoid trying to set a Model\u8217's attributes directly (for example, {\f1 Model.caption = 'A new caption'}). Backbone uses Model.set() to know when to broadcast that a model\u8217's data has changed.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
initialize: function()\{\line
console.log('this model has been initialized');\line
\}\line
\});\line
\line
// Setting the value of attributes via instantiation\line
var myPhoto = new Photo(\{ title: 'My awesome photo', location: 'Boston' \});\line
\line
var myPhoto2 = new Photo();\line
\line
// Setting the value of attributes through Model.set()\line
myPhoto2.set(\{ title:'Vacation in Florida', location: 'Florida' \});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Default values}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There are times when you want your model to have a set of default values (e.g.\u160?in a scenario where a complete set of data isn\u8217't provided by the user). This can be set using a property called {\f1 defaults} in your model.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
defaults: \{\line
title: 'Another photo!',\line
tags: ['untagged'],\line
location: 'home',\line
src: 'placeholder.jpg'\line
\},\line
initialize: function()\{\line
\}\line
\});\line
\line
var myPhoto = new Photo(\{ location: "Boston",\line
tags:['the big game', 'vacation']\}),\line
title = myPhoto.get("title"), //Another photo!\line
location = myPhoto.get("location"), //Boston\line
tags = myPhoto.get("tags"), // ['the big game','vacation']\line
photoSrc = myPhoto.get("src"); //placeholder.jpg\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Listening for changes to your model}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Any and all of the attributes in a Backbone model can have listeners bound to them which detect when their values change. Listeners can be added to the {\f1 initialize()} function:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 this.on('change', function()\{\line
console.log('values for this model have changed');\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In the following example, we log a message whenever a specific attribute (the title of our Photo model) is altered.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
defaults: \{\line
title: 'Another photo!',\line
tags: ['untagged'],\line
location: 'home',\line
src: 'placeholder.jpg'\line
\},\line
initialize: function()\{\line
console.log('this model has been initialized');\line
this.on("change:title", function()\{\line
var title = this.get("title");\line
console.log("My title has been changed to.. " + title);\line
\});\line
\},\line
\line
setTitle: function(newTitle)\{\line
this.set(\{ title: newTitle \});\line
\}\line
\});\line
\line
var myPhoto = new Photo(\{ title:"Fishing at the lake", src:"fishing.jpg"\});\line
myPhoto.setTitle('Fishing at sea');\line
//logs 'My title has been changed to.. Fishing at sea'\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Validation}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone supports model validation through {\f1 Model.validate()}, which allows checking the attribute values for a model prior to them being set.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from {\f1 .validate()}. If they are invalid, a custom error can be returned instead.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 A basic example for validation can be seen below:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var Photo = Backbone.Model.extend(\{\line
validate: function(attribs)\{\line
if(attribs.src === undefined)\{\line
return "Remember to set a source for your image!";\line
\}\line
\},\line
\line
initialize: function()\{\line
console.log('this model has been initialized');\line
this.on("error", function(model, error)\{\line
console.log(error);\line
\});\line
\}\line
\});\line
\line
var myPhoto = new Photo();\line
myPhoto.set(\{ title: "On the beach" \});\line
//logs Remember to set a source for your image!\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Note}: Backbone passes the {\f1 attributes} object by shallow copy to the {\f1 validate} function using the Underscore {\f1 _.extend} method. This means that it is not possible to change any Number, String or Boolean attribute but it {\i is} possible to change attributes of objects because they are passed by reference. As shallow copy doesn\u8217't copy objects by implicitly copying them, but rather, by reference, one can change the attributes on those objects.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 An example of this (by @fivetanley) is available {\field{\*\fldinst{HYPERLINK "http://jsfiddle.net/2NdDY/7/"}}{\fldrslt{\ul
here
}}}
.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Views\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Views in Backbone don\u8217't contain the markup for your application, but rather they are there to support models by defining the logic for how they should be represented to the user. This is usually achieved using JavaScript templating (e.g.\u160?Mustache, jQuery-tmpl, etc.). A view\u8217's {\f1 render()} function can be bound to a model\u8217's {\f1 change()} event, allowing the view to always be up to date without requiring a full page refresh.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Creating new views\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Similar to the previous sections, creating a new view is relatively straight-forward. To create a new View, simply extend {\f1 Backbone.View}. I\u8217'll explain this code in detail below:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoSearch = Backbone.View.extend(\{\line
el: $('#results'),\line
render: function( event )\{\line
var compiled_template = _.template( $("#results-template").html() );\line
this.$el.html( compiled_template(this.model.toJSON()) );\line
return this; //recommended as this enables calls to be chained.\line
\},\line
events: \{\line
"submit #searchForm": "search",\line
"click .reset": "reset",\line
"click .advanced": "switchContext"\line
\},\line
search: function( event )\{\line
//executed when a form '#searchForm' has been submitted\line
\},\line
reset: function( event )\{\line
//executed when an element with class "reset" has been clicked.\line
\},\line
switchContext: function( event )\{\line
//executed when an element with class "advanced" has been clicked.\line
\}\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 What is {\f1 el}?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 el} is basically a reference to a DOM element and all views must have one. It allows for all of the contents of a view to be inserted into the DOM at once, which makes for faster rendering because the browser performs the minimum required reflows and repaints.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There are two ways to attach a DOM element to a view: the element already exists in the page or a new element is created for the view and added manually by the developer. If the element already exists in the page, you can set {\f1 el} as either a CSS selector that matches the element or a simple reference to the DOM element.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 el: '#footer',\line
// OR\line
el: document.getElementById( 'footer' )\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If you want to create a new element for your view, set any combination of the following view\u8217's properties: {\f1 tagName}, {\f1 id} and {\f1 className}. A new element will be created for you by the framework and a reference to it will be available at the {\f1 el} property.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 tagName: 'p', // required, but defaults to 'div' if not set\line
className: 'container', // optional, you can assign multiple classes to this property like so 'container homepage'\line
id: 'header', // optional\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The above code creates the {\f1 DOMElement} below but doesn\u8217't append it to the DOM.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 <p id="header" class="container"></p>\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Understanding {\f1 render()}}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 render()} is an optional function that defines the logic for rendering a template. We\u8217'll use Underscore\u8217's micro-templating in these examples, but remember you can use other templating frameworks if you prefer.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The {\f1 _.template} method in Underscore compiles JavaScript templates into functions which can be evaluated for rendering. In the above view, I\u8217'm passing the markup from a template with id {\f1 results-template} to {\f1 _.template()} to be compiled. Next, I set the html of the {\f1 el} DOM element to the output of processing a JSON version of the model associated with the view through the compiled template.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Presto! This populates the template, giving you a data-complete set of markup in just a few short lines of code.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b The {\f1 events} attribute}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The Backbone {\f1 events} attribute allows us to attach event listeners to either custom selectors, or directly to {\f1 el} if no selector is provided. An event takes the form {\f1 \{"eventName selector": "callbackFunction"\}} and a number of DOM event-types are supported, including {\f1 click}, {\f1 submit}, {\f1 mouseover}, {\f1 dblclick} and more.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 What isn\u8217't instantly obvious is that under the bonnet, Backbone uses jQuery\u8217's {\f1 .delegate()} to provide instant support for event delegation but goes a little further, extending it so that {\f1 this} always refers to the current view object. The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Collections\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Collections are sets of Models and are created by extending {\f1 Backbone.Collection}.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Normally, when creating a collection you\u8217'll also want to pass through a property specifying the model that your collection will contain, as well as any instance properties required.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In the following example, we create a PhotoCollection that will contain our Photo models:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoCollection = Backbone.Collection.extend(\{\line
model: Photo\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Getters and Setters}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There are a few different ways to retrieve a model from a collection. The most straight-forward is to use {\f1 Collection.get()} which accepts a single id as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var skiingEpicness = PhotoCollection.get(2);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Sometimes you may also want to get a model based on its client id. The client id is a property that Backbone automatically assigns models that have not yet been saved. You can get a model\u8217's client id from its {\f1 .cid} property.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var mySkiingCrash = PhotoCollection.getByCid(456);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone Collections don\u8217't have setters as such, but do support adding new models via {\f1 .add()} and removing models via {\f1 .remove()}.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var a = new Photo(\{ title: 'my vacation'\}),\line
b = new Photo(\{ title: 'my holiday'\}),\line
c = new Photo(\{ title: 'my weekend'\});\line
\line
var photoCollection = new PhotoCollection([a,b]);\line
photoCollection.add(c);\line
\line
photoCollection.remove([a,b]);\line
photoCollection.remove(c);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Listening for events}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As collections represent a group of items, we\u8217're also able to listen for {\f1 add} and {\f1 remove} events for when new models are added or removed from the collection. Here\u8217's an example:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoCollection = new Backbone.Collection();\line
PhotoCollection.on("add", function(photo) \{\line
console.log("I liked " + photo.get("title") + ' it\\'s this one, right? ' + photo.get("src"));\line
\});\line
\line
PhotoCollection.add([\line
\{title: "My trip to Bali", src: "bali-trip.jpg"\},\line
\{title: "The flight home", src: "long-flight-oofta.jpg"\},\line
\{title: "Uploading pix", src: "too-many-pics.jpg"\}\line
]);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In addition, we\u8217're able to bind a {\f1 change} event to listen for changes to models in the collection.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 PhotoCollection.on("change:title", function()\{\line
console.log("there have been updates made to this collection's titles");\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Fetching models from the server}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 Collections.fetch()} retrieves a default set of models from the server in the form of a JSON array. When this data returns, the current collection\u8217's contents will be replaced with the contents of the array.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var PhotoCollection = new Backbone.Collection;\line
PhotoCollection.url = '/photos';\line
PhotoCollection.fetch();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 During configuration, Backbone sets a variable to denote if extended HTTP methods are supported by the server. Another setting controls if the server understands the correct MIME type for JSON:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Backbone.emulateHTTP = false;\line
Backbone.emulateJSON = false;\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The Backbone.sync method that uses these values is actually an integral part of Backbone.js. A jQuery-like ajax method is assumed, so HTTP parameters are organised based on jQuery\u8217's API. Searching through the code for calls to the sync method show it\u8217's used whenever a model is saved, fetched, or deleted (destroyed).\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Under the covers, {\f1 Backbone.sync} is the function called every time Backbone tries to read or save models to the server. It uses jQuery or Zepto\u8217's ajax implementations to make these RESTful requests, however this can be overridden as per your needs. :\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The sync function may be overriden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 There\u8217's no fancy plugin API for adding a persistence layer \u8211- simply override Backbone.sync with the same function signature:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Backbone.sync = function(method, model, options) \{\line
\};\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The default methodMap is useful for working out what the method argument does:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var methodMap = \{\line
'create': 'POST',\line
'update': 'PUT',\line
'delete': 'DELETE',\line
'read': 'GET'\line
\};\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In the above example if we wanted to log an event when {\f1 .sync()} was called, we could do this:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var id_counter = 1;\line
Backbone.sync = function(method, model) \{\line
console.log("I've been passed " + method + " with " + JSON.stringify(model));\line
if(method === 'create')\{ model.set('id', id_counter++); \}\line
\};\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Resetting/Refreshing Collections}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Rather than adding or removing models individually, you might occasionally wish to update an entire collection at once. {\f1 Collection.reset()} allows us to replace an entire collection with new models as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 PhotoCollection.reset([\line
\{title: "My trip to Scotland", src: "scotland-trip.jpg"\},\line
\{title: "The flight from Scotland", src: "long-flight.jpg"\},\line
\{title: "Latest snap of Loch Ness", src: "lochness.jpg"\}]);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Note that using {\f1 Collection.reset()} doesn\u8217't fire any {\f1 add} or {\f1 remove} events. A {\f1 reset} event is fired instead.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Underscore utility functions\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As Backbone requires Underscore as a hard dependency, we\u8217're able to use many of the utilities it has to offer to aid with our application development. Here\u8217's an example of how Underscore\u8217's {\f1 sortBy()} method can be used to sort a collection of photos based on a particular attribute.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var sortedByAlphabet = PhotoCollection.sortBy(function (photo) \{\line
return photo.get("title").toLowerCase();\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The complete list of what Underscore can do is beyond the scope of this guide, but can be found in its official {\field{\*\fldinst{HYPERLINK "http://documentcloud.github.com/underscore/"}}{\fldrslt{\ul
docs
}}}
.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Chainable API\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Speaking of utility methods, another bit of sugar in Backbone is the support for Underscore\u8217's chain method. This works by calling the original method with the current array of models and returning the result. In case you haven\u8217't seen it before, the chainable API looks like this:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var collection = new Backbone.Collection([\line
\{ name: 'Tim', age: 5 \},\line
\{ name: 'Ida', age: 26 \},\line
\{ name: 'Rob', age: 55 \}\line
]);\line
\line
collection.chain()\line
.filter(function(item) \{ return item.get('age') > 10; \})\line
.map(function(item) \{ return item.get('name'); \})\line
.value();\line
\line
// Will return ['Ida', 'Rob']\line
\line
Some of the Backbone-specific methods will return this, which means they can be chained as well:\line
\line
var collection = new Backbone.Collection();\line
\line
collection\line
.add(\{ name: 'John', age: 23 \})\line
.add(\{ name: 'Harry', age: 33 \})\line
.add(\{ name: 'Steve', age: 41 \});\line
\line
collection.pluck('name');\line
// ['John', 'Harry', 'Steve']\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Events\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As we\u8217've covered, Backbone\u8217's objects are designed to be inherited from and every single one of the following objects inherits from {\f1 Backbone.Events}:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Backbone.Model\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Backbone.Collection\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Backbone.Router\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Backbone.History\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Backbone.View\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Events are the standard way to deal with user interface actions, through the declarative event bindings on views, and also model and collection changes. Mastering events is one of the quickest ways to become more productive with Backbone.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 Backbone.Events} also has the ability to give any object a way to bind and trigger custom events. We can mix this module into any object easily and there isn\u8217't a requirement for events to be declared prior to them being bound.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Example:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var ourObject = \{\};\line
\line
// Mixin\line
_.extend(ourObject, Backbone.Events);\line
\line
// Add a custom event\line
ourObject.on("dance", function(msg)\{\line
console.log("We triggered " + msg);\line
\});\line
\line
// Trigger the custom event\line
ourObject.trigger("dance", "our event");\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If you\u8217're familiar with jQuery custom events or the concept of Publish/Subscribe, {\f1 Backbone.Events} provides a system that is very similar with {\f1 on} being analogous to {\f1 subscribe} and {\f1 trigger} being similar to {\f1 publish}.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 on} basically allows us to bind a callback function to any object, as we\u8217've done with {\f1 dance} in the above example. Whenever the event is fired, our callback is invoked.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The official Backbone.js documentation recommends namespacing event names using colons if you end up using quite a few of these on your page. e.g:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 ourObject.on("dance:tap", ...);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 A special {\f1 all} event is made available in case you would like an event to be triggered when any event occurs (e.g if you would like to screen events in a single location). The {\f1 all} event can be used as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 ourObject.on("all", function(eventName)\{\line
console.log("The name of the event passed was " + eventName);\line
\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\f1 off} allows us to remove a callback function that has previously been bound from an object. Going back to our Publish/Subscribe comparison, think of it as an {\f1 unsubscribe} for custom events.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 To remove the {\f1 dance} event we previously bound to {\f1 myObject}, we would simply do:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 myObject.off("dance");\par}
{\pard \ql \f0 \sa180 \li0 \fi0 This will remove all callbacks for the {\f1 dance} event. If we wish to remove just a callback by a specific name, we can do:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 myObject.off("dance", callbackName);\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Finally, {\f1 trigger} triggers a callback for a specified event (or a space-separated listof events). e.g:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 // Single event\line
myObject.trigger("dance");\line
\line
// Multiple events\line
myObject.trigger("dance jump skip");\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It is also possible to pass along additional arguments to each (or all) of these events via a second argument supported by {\f1 trigger}. e.g:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 myObject.trigger("dance", \{duration: "5 minutes"\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Routers\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In Backbone, routers are used to help manage application state and for connecting URLs to application events. This is achieved using hash-tags with URL fragments, or using the browser\u8217's pushState and History API. Some examples of routes may be seen below:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 http://unicorns.com/#whatsup\line
http://unicorns.com/#search/seasonal-horns/page2\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Note: An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that particular route. This relationship is defined as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 "route" : "mappedFunction"\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Let us now define our first controller by extending {\f1 Backbone.Router}. For the purposes of this guide, we\u8217're going to continue pretending we\u8217're creating a photo gallery application that requires a GalleryRouter.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Note the inline comments in the code example below as they continue the rest of the lesson on routers.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var GalleryRouter = Backbone.Router.extend(\{\line
/* define the route and function maps for this router */\line
routes: \{\line
"about" : "showAbout",\line
/*Sample usage: http://unicorns.com/# <about*/\line
\line
"photos/:id" : "getPhoto",\line
/*This is an example of using a ":param" variable which allows us to match\line
any of the components between two URL slashes*/\line
/*Sample usage: http://unicorns.com/#photos/5*/\line
\line
"search/:query" : "searchPhotos",\line
/*We can also define multiple routes that are bound to the same map function,\line
in this case searchPhotos(). Note below how we're optionally passing in a\line
reference to a page number if one is supplied*/\line
/*Sample usage: http://unicorns.com/#search/lolcats*/\line
\line
"search/:query/p:page" : "searchPhotos",\line
/*As we can see, URLs may contain as many ":param"s as we wish*/\line
/*Sample usage: http://unicorns.com/#search/lolcats/p1*/\line
\line
"photos/:id/download/*imagePath" : "downloadPhoto",\line
/*This is an example of using a *splat. splats are able to match any number of\line
URL components and can be combined with ":param"s*/\line
/*Sample usage: http://unicorns.com/#photos/5/download/files/lolcat-car.jpg*/\line
\line
/*If you wish to use splats for anything beyond default routing, it's probably a good\line
idea to leave them at the end of a URL otherwise you may need to apply regular\line
expression parsing on your fragment*/\line
\line
"*other" : "defaultRoute"\line
/*This is a default route that also uses a *splat. Consider the\line
default route a wildcard for URLs that are either not matched or where\line
the user has incorrectly typed in a route path manually*/\line
/*Sample usage: http://unicorns.com/# <anything*/\line
\line
\},\line
\line
showAbout: function()\{\line
\},\line
\line
getPhoto: function(id)\{\line
/*\line
Note that the id matched in the above route will be passed to this function\line
*/\line
console.log("You are trying to reach photo " + id);\line
\},\line
\line
searchPhotos: function(query, page)\{\line
var page_number = page || 1;\line
console.log("Page number: " + page_number + " of the results for " + query);\line
\},\line
\line
downloadPhoto: function(id, path)\{\line
\},\line
\line
defaultRoute: function(other)\{\line
console.log("Invalid. You attempted to reach:" + other);\line
\}\line
\});\line
\line
/* Now that we have a router setup, remember to instantiate it*/\line
\line
var myGalleryRouter = new GalleryRouter();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As of Backbone 0.5+, it\u8217's possible to opt-in for HTML5 pushState support via {\f1 window.history.pushState}. This permits you to define routes such as http://www.scriptjunkie.com/just/an/example. This will be supported with automatic degradation when a user\u8217's browser doesn\u8217't support pushState. For the purposes of this tutorial, we\u8217'll use the hashtag method.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Is there a limit to the number of routers I should be using?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Andrew de Andrade has pointed out that DocumentCloud themselves usually only use a single router in most of their applications. You\u8217're very likely to not require more than one or two routers in your own projects as the majority of your application routing can be kept organized in a single controller without it getting unwieldy.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Backbone.history\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Next, we need to initialize {\f1 Backbone.history} as it handles {\f1 hashchange} events in our application. This will automatically handle routes that have been defined and trigger callbacks when they\u8217've been accessed.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The {\f1 Backbone.history.start()} method will simply tell Backbone that it\u8217's OK to begin monitoring all {\f1 hashchange} events as follows:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 Backbone.history.start();\line
Router.navigate();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As an aside, if you would like to save application state to the URL at a particular point you can use the {\f1 .navigate()} method to achieve this. It simply updates your URL fragment without the need to trigger the {\f1 hashchange} event:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 /*Lets imagine we would like a specific fragment for when a user zooms into a photo*/\line
zoomPhoto: function(factor)\{\line
this.zoom(factor); //imagine this zooms into the image\line
this.navigate("zoom/" + factor); //updates the fragment for us, but doesn't trigger the route\line
\}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It is also possible for {\f1 Router.navigate()} to trigger the route as well as updating the URL fragment.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 zoomPhoto: function(factor)\{\line
this.zoom(factor); //imagine this zooms into the image\line
this.navigate("zoom/" + factor, true); //updates the fragment for us and triggers the route\line
\}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Backbone\u8217's Sync API\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The Backbone.sync method is intended to be overridden to support other backends. The built-in method is tailed to a certain breed of RESTful JSON APIs \u8211- Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT the same way.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The way this works is the model and collection classes have a sync method that calls Backbone.sync. Both will call this.sync internally when fetching, saving, or deleting items.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The sync method is called with three parameters:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab method: One of create, update, delete, read\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab model: The Backbone model object\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab options: May include success and error methods\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Implementing a new sync method can use the following pattern:\par}