forked from addyosmani/backbone-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-fundamentals.rtf
4581 lines (4580 loc) · 351 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 in a few months time 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 \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 \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 "#thebasics"}}{\fldrslt{\ul
The Basics
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#models"}}{\fldrslt{\ul
Models
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#views"}}{\fldrslt{\ul
Views
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#collections"}}{\fldrslt{\ul
Collections
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#routers"}}{\fldrslt{\ul
Routers
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#namespacing"}}{\fldrslt{\ul
Namespacing
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#additional-tips"}}{\fldrslt{\ul
Additional tips
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li360 \fi-360 \bullet \tx360\tab \b \fs24 {\field{\*\fldinst{HYPERLINK "#restfulapps"}}{\fldrslt{\ul
RESTful Applications
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#restful"}}{\fldrslt{\ul
Building RESTful applications with Backbone
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#stack1"}}{\fldrslt{\ul
Building Backbone 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
Building Backbone 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 {\field{\*\fldinst{HYPERLINK "#advanced"}}{\fldrslt{\ul
Advanced
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#modularjs"}}{\fldrslt{\ul
Modular JavaScript
}}}
\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 with the RequireJS text plugin
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#optimizingrequirejs"}}{\fldrslt{\ul
Optimizing Backbone apps for production with the RequireJS Optimizer
}}}
\par}
{\pard \ql \f0 \sa0 \li720 \fi-360 \endash \tx360\tab {\field{\*\fldinst{HYPERLINK "#practicalrequirejs"}}{\fldrslt{\ul
Practical: Building a modular Backbone app with AMD & RequireJS
}}}
\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
}}}
\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 {\field{\*\fldinst{HYPERLINK "#testing-jasmine-models"}}{\fldrslt{\ul
Testing Models
}}}
\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab {\field{\*\fldinst{HYPERLINK "#testing-jasmine-collections"}}{\fldrslt{\ul
Testing Collections
}}}
\par}
{\pard \ql \f0 \sa0 \li1080 \fi-360 \bullet \tx360\tab {\field{\*\fldinst{HYPERLINK "#testing-jasmine-views"}}{\fldrslt{\ul
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 \fs32 Introduction\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As JavaScript developers, we are at an interesting point in time where not only do we have mature solutions to help organize the JavaScript powering our applications based on a separation of concerns, but developers looking to build non-trivial projects are almost spoiled for choice for frameworks that can help structure their applications.\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 In this book, I will be covering the popular Backbone.js, which I consider the best of the current family of JavaScript architectural frameworks.\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 If this is your first time looking at Backbone.js and you\u8217're still unsure whether or not to give it a try, why not take a look at how {\field{\*\fldinst{HYPERLINK "http://github.com/addyosmani/todomvc"}}{\fldrslt{\ul
a Todo application
}}}
can be implemented in Backbone and several other popular Javascript frameworks before reading further?\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 \b \fs32 Fundamentals\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section we are going to cover the context into which a framework like Backbone.js fits. Let\u8217's begin our journey into understanding Backbone better with a look at code architecture.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 MVC, MVP & Backbone.js\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. 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 far and few 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 (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 deliminated 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 a 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.\line \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\line \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, your 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 as 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")\line \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.bind('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.bind('change', this.render);\line
this.model.bind('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\line \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 \fs32 ## The Basics\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 What is Backbone?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone.js is one of a number of JavaScript frameworks for creating MVC-like web applications. On the front-end, it\u8217's my architectural framework of choice as it\u8217's both mature, relatively lightweight and can be easily tested using third-party toolkits such as Jasmine or QUnit. Other MVC frameworks you may be familiar with include Ember.js (SproutCore 2.0), Spine, YUILibrary and JavaScriptMVC.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone is maintained by a number of contributors, most notably: Jeremy Ashkenas, creator of CoffeeScript, Docco and Underscore.js. As Jeremy is a believer in detailed documentation, there\u8217's a level of comfort in knowing you\u8217're unlikely to run into issues which are either not explained in the official docs or which can\u8217't be nailed down with some assistance from the #documentcloud IRC channel. I strongly recommend using the latter if you find yourself getting stuck.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Why should you consider using it?\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 \fs32 The Basics\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 \fs28 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.bind("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 {\f1 Model.toJSON()}:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myAttributes = myPhoto.toJSON();\line
console.log(myAttributes);\line
/* this returns \{ title: "My awesome photo", \line
src:"boston.jpg", \line
location: "Boston", \line
tags:['the big game', 'vacation']\}*/\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 Model.caption = \u8216'A new caption\u8217'). 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.bind('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.bind("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.bind("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 \fs28 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 as 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 you 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 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 \fs28 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 Backbone.Model(\{ title: 'my vacation'\}),\line
b = new Backbone.Model(\{ title: 'my holiday'\});\line
\line
var photoCollection = new PhotoCollection([a,b]);\line
photoCollection.remove([a,b]);\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.bind("add", function(photo) \{\line
console.log("I liked " + photo.get("title") + ' its 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.bind("change:title", function()\{\line
console.log('there have been updates made to this collections 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 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 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 Backbone.sync = function(method, model) \{\line
console.log("I've been passed " + method + " with " + JSON.stringify(model));\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 lock-ness", src: "lockness.jpg"\}]);\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 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
console.log("Page number: " + page + " 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 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 Namespacing\par}
{\pard \ql \f0 \sa180 \li0 \fi0 When learning how to use Backbone, an important and commonly overlooked area by tutorials is namespacing. If you already have experience with namespacing in JavaScript, the following section will provide some advice on how to specifically apply concepts you know to Backbone, however I will also be covering explanations for beginners to ensure everyone is on the same page.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 What is namespacing?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The basic idea around namespacing is to avoid collisions with other objects or variables in the global namespace. They\u8217're important as it\u8217's best to safeguard your code from breaking in the event of another script on the page using the same variable names as you are. As a good \u8216'citizen\u8217' of the global namespace, it\u8217's also imperative that you do your best to similarly not prevent other developer\u8217's scripts executing due to the same issues.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 JavaScript doesn\u8217't really have built-in support for namespaces like other languages, however it does have closures which can be used to achieve a similar effect.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section we\u8217'll be taking a look shortly at some examples of how you can namespace your models, views, routers and other components specifically. The patterns we\u8217'll be examining are:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Single global variables\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Object Literals\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab Nested namespacing\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Single global variables}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myApplication = (function()\{\line
function()\{\line
// ...\line
\},\line
return \{\line
// ...\line
\}\line
\})();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 You\u8217've probably seen this technique before. A Backbone-specific example might look like this:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myViews = (function()\{\line
return \{\line
PhotoView: Backbone.View.extend(\{ .. \}),\line
GalleryView: Backbone.View.extend(\{ .. \}),\line
AboutView: Backbone.View.extend(\{ .. \});\line
//etc.\line
\};\line
\})();\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Here we can return a set of views, but the same technique could return an entire collection of models, views and routers depending on how you decide to structure your application. Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 One solution to this problem, as mentioned by Peter Michaux, is to use prefix namespacing. It\u8217's a simple concept at heart, but the idea is you select a common prefix name (in this example, {\f1 myApplication_}) and then define any methods, variables or other objects after the prefix.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myApplication_photoView = Backbone.View.extend(\{\}),\line
myApplication_galleryView = Backbone.View.extend(\{\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 For more on Peter\u8217's views about the single global variable pattern, read his {\field{\*\fldinst{HYPERLINK "http://michaux.ca/articles/javascript-namespacing"}}{\fldrslt{\ul
excellent post on them
}}}
.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Note: There are several other variations on the single global variable pattern out in the wild, however having reviewed quite a few, I felt the prefixing approach applied best to Backbone.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Object Literals}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Object Literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They\u8217're beneficial if you wish to create easily readable structures that can be expanded to support deep nesting. Unlike simple global variables, Object Literals often also take into account tests for the existence of a variable by the same name, which helps reduce the chances of collision.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 This example demonstrates two ways you can check to see if a namespace already exists before defining it. I commonly use Option 2.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 /*Doesn't check for existence of myApplication*/\line
var myApplication = \{\};\line
\line
/*\line
Does check for existence. If already defined, we use that instance.\line
Option 1: if(!myApplication) myApplication = \{\};\line
Option 2: var myApplication = myApplication || \{\};\line
We can then populate our object literal to support models, views and collections (or any data, really):\line
*/\line
\line
var myApplication = \{\line
models : \{\},\line
views : \{\line
pages : \{\}\line
\},\line
collections : \{\}\line
\};\par}
{\pard \ql \f0 \sa180 \li0 \fi0 One can also opt for adding properties directly to the namespace (such as your views, in the following example):\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myGalleryViews = myGalleryViews || \{\};\line
myGalleryViews.photoView = Backbone.View.extend(\{\});\line
myGalleryViews.galleryView = Backbone.View.extend(\{\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The benefit of this pattern is that you\u8217're able to easily encapsulate all of your models, views, routers etc. in a way that clearly separates them and provides a solid foundation for extending your code.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 This pattern has a number of benefits. It\u8217's often a good idea to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter it. Here\u8217's an example of a hypothetical object literal that stores application configuration settings:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var myConfig = \{\line
language: 'english',\line
defaults: \{\line
enableGeolocation: true,\line
enableSharing: false,\line
maxPhotos: 20\line
\},\line
theme: \{\line
skin: 'a',\line
toolbars: \{\line
index: 'ui-navigation-toolbar',\line
pages: 'ui-custom-toolbar' \line
\}\line
\}\line
\}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Note that there are really only minor syntactical differences between the Object Literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g.\u160?for simpler storage when sending to the back-end), feel free to.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 For more on the Object Literal pattern, I recommend reading Rebecca Murphey\u8217's {\field{\*\fldinst{HYPERLINK "http://blog.rebeccamurphey.com/2009/10/15/using-objects-to-organize-your-code"}}{\fldrslt{\ul
excellent article on the topic
}}}
.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Nested namespacing}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 An extension of the Object Literal pattern is nested namespacing. It\u8217's another common pattern used that offers a lower risk of collision due to the fact that even if a top-level namespace already exists, it\u8217's unlikely the same nested children do. For example, Yahoo\u8217's YUI uses the nested object namespacing pattern extensively:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 YAHOO.util.Dom.getElementsByClassName('test');\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Yahoo\u8217's YUI uses the nested object namespacing pattern regularly and even DocumentCloud (the creators of Backbone) use the nested namespacing pattern in their main applications. A sample implementation of nested namespacing with Backbone may look like this:\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \f1 var galleryApp = galleryApp || \{\};\line
\line
// perform similar check for nested children\line
galleryApp.routers = galleryApp.routers || \{\};\line
galleryApp.model = galleryApp.model || \{\};\line
galleryApp.model.special = galleryApp.model.special || \{\};\line
\line
// routers\line
galleryApp.routers.Workspace = Backbone.Router.extend(\{\}); \line
galleryApp.routers.PhotoSearch = Backbone.Router.extend(\{\}); \line
\line
// models\line
galleryApp.model.Photo = Backbone.Model.extend(\{\});\line
galleryApp.model.Comment = Backbone.Model.extend(\{\}); \line
\line
// special models\line
galleryApp.model.special.Admin = Backbone.Model.extend(\{\});\par}
{\pard \ql \f0 \sa180 \li0 \fi0 This is readable, clearly organized, and is a relatively safe way of namespacing your Backbone application. The only real caveat however is that it requires your browser\u8217's JavaScript engine to first locate the galleryApp object, then dig down until it gets to the function you\u8217're calling. However, developers such as Juriy Zaytsev (kangax) have tested and found the performance differences between single object namespacing vs the \u8216'nested\u8217' approach to be quite negligible.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 {\b Recommendation}\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Reviewing the namespace patterns above, the option that I prefer when writing Backbone applications is nested object namespacing with the object literal pattern.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Single global variables may work fine for applications that are relatively trivial. However, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that\u8217's both readable and scalable. I feel this pattern achieves both of these objectives and is a good choice for most Backbone development.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Additional Tips\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs24 Automated Backbone Scaffolding\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Scaffolding can assist in expediting how quickly you can begin a new application by creating the basic files required for a project automatically. If you enjoy the idea of automated MVC scaffolding using Backbone, I\u8217'm happy to recommend checking out a tool called {\field{\*\fldinst{HYPERLINK "https://github.com/brunch/brunch"}}{\fldrslt{\ul
Brunch
}}}
.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 It works very well with Backbone, Underscore, jQuery and CoffeeScript and is even used by companies such as Red Bull and Jim Beam. You may have to update any third party dependencies (e.g.\u160?latest jQuery or Zepto) when using it, but other than that it should be fairly stable to use right out of the box.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Brunch can be installed via the nodejs package manager and is easy to get started with. If you happen to use Vim or Textmate as your editor of choice, you\u8217'll be happy to know that there are Brunch bundles available for both.\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 Is Backbone too small for my application\u8217's needs?\par}
{\pard \ql \f0 \sa180 \li0 \fi0 If you find yourself unsure of whether or not your application is too large to use Backbone, I recommend reading my post on building large-scale jQuery & JavaScript applications or reviewing my slides on client-side MVC architecture options. In both, I cover alternative solutions and my thoughts on the suitability of current MVC solutions for scaled application development.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Backbone can be used for building both trivial and complex applications as demonstrated by the many examples Ashkenas has been referencing in the Backbone documentation. As with any MVC framework however, it\u8217's important to dedicate time towards planning out what models and views your application really needs. Diving straight into development without doing this can result in either spaghetti code or a large refactor later on and it\u8217's best to avoid this where possible.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 At the end of the day, the key to building large applications is not to build large applications in the first place. If you however find Backbone doesn\u8217't cut it for your requirements I strongly recommend checking out JavaScriptMVC or SproutCore as these both offer a little more than Backbone out of the box. Dojo and Dojo Mobile may also be of interest as these have also been used to build significantly complex apps by other developers.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 ## RESTful Applications\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Building RESTful applications with Backbone\par}
{\pard \ql \f0 \sa180 \li0 \fi0 In this section of the book, we\u8217're going to take a look at developing RESTful applications using Backbone.js and modern technology stacks. When the data for your back-end is exposed through a purely RESTful API, tasks such as retrieving (GET), creating (POST), updating (PUT) and deleting (DELETE) models are made easy through Backbone\u8217's Model API. This API is so intuitive in fact that switching from storing records in a local data-store (e.g localStorage) to a database/noSQL data-store is a lot simpler than you may think.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Stack 1: Building A Backbone App With Node.js, Express, Mongoose and MongoDB\par}
{\pard \ql \f0 \sa180 \li0 \fi0 The first stack we\u8217'll be looking at is:\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\field{\*\fldinst{HYPERLINK "nodejs.org"}}{\fldrslt{\ul
Node.js
}}}
\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\field{\*\fldinst{HYPERLINK "http://expressjs.com/"}}{\fldrslt{\ul
Express
}}}
\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab {\field{\*\fldinst{HYPERLINK "http://mongoosejs.com/"}}{\fldrslt{\ul
Mongoose
}}}
\par}
{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab and {\field{\*\fldinst{HYPERLINK "http://www.mongodb.org/"}}{\fldrslt{\ul
MongoDB
}}}
\sa180\par}
{\pard \ql \f0 \sa180 \li0 \fi0 with {\field{\*\fldinst{HYPERLINK "http://jade-lang.com/"}}{\fldrslt{\ul
Jade
}}}
used optionally as a view/templating engine.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Reviewing the stack\par}
{\pard \ql \f0 \sa180 \li0 \fi0 As you may know, node.js is an event-driven platform (built on the {\field{\*\fldinst{HYPERLINK "http://code.google.com/apis/v8/design.html"}}{\fldrslt{\ul
V8
}}}
runtime), designed for writing fast, scalable network applications. It\u8217's reasonably lightweight, efficient and great for real-time applications that are data-intensive.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Express is a small web-development framework written with node.js, based on {\field{\*\fldinst{HYPERLINK "http://www.sinatrarb.com/"}}{\fldrslt{\ul
Sinatra
}}}
. It supports a number of useful features such as intuitive views, robust routing and a focus on high performance.\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Next on the list are MongoDB and Mongoose. MongoDB is an open-source, document-oriented database store designed with scalability and agility in mind. As a {\field{\*\fldinst{HYPERLINK "http://en.wikipedia.org/wiki/NoSQL"}}{\fldrslt{\ul
noSQL
}}}
database, rather than storing data in tables and rows (something we\u8217're very used to doing with relational databases), with MongoDB we instead store JSON-like documents using dynamic schemas. One of the goals of Mongo is to try bridging the gap between key-value stores (speed, scalability) and {\field{\*\fldinst{HYPERLINK "http://en.wikipedia.org/wiki/Relational_database"}}{\fldrslt{\ul
relational
}}}
databases (rich functionality).\par}
{\pard \ql \f0 \sa180 \li0 \fi0 Mongoose is a JavaScript library that simplifies how we interact with Mongo. Like Express, it\u8217's designed to work within the node.js environment and tries to solve some of the complexities with asynchronous data storage by offering a more user-friendly API. It also adds chaining features into the mix, allowing for a slightly more expressive way of dealing with our data.\par}