forked from addyosmani/backbone-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
8994 lines (7966 loc) · 840 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Developing Backbone.js Applications - </title>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
q { quotes: "“" "”" "‘" "’"; }
</style>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #40a070; }
code > span.fl { color: #40a070; }
code > span.ch { color: #4070a0; }
code > span.st { color: #4070a0; }
code > span.co { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > span.er { color: #ff0000; font-weight: bold; }
</style>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p>
<h1>Developing Backbone.js Applications</h1>
<h3>By Addy Osmani <a href="http://twitter.com/addyosmani">@addyosmani</a></h3>
</p>
<div style="width:500px">
<iframe src="http://ghbtns.com/github-btn.html?user=addyosmani&repo=backbone-fundamentals&type=watch&count=true"
allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.1333103182.html#_=1333404284780&count=horizontal&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Faddyosmani.github.com%2Fbackbone-fundamentals%2F&size=m&text=Developing%20Backbone.js%20Applications&url=https%3A%2F%2Fgithub.com%2Faddyosmani%2Fbackbone-fundamentals&via=addyosmani" class="twitter-share-button twitter-count-horizontal" style="width: 107px; height: 20px; " title="Twitter Tweet Button"></iframe>
<script id="twitter-wjs" src="//platform.twitter.com/widgets.js"></script><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<p> <br></p>
</div>
<p><img src="img/oreilly.jpg"/></p>
<a href="http://shop.oreilly.com/product/0636920025344/ReviewSubmit.do?sortby=publicationDate?pageId=0636920025344.IP"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://addyosmani.github.com/backbone-fundamentals/img/helpful.png" alt="Was this helpful? We'd love you to write a review."></a>
<nav id="TOC">
<ul>
<li><a href="#prelude">Prelude</a></li>
<li><a href="#target-audience">Target Audience</a></li>
<li><a href="#acknowledgements">Acknowledgements</a></li>
<li><a href="#credits">Credits</a></li>
<li><a href="#reading">Reading</a></li>
<li><a href="#introduction">Introduction</a><ul>
<li><a href="#what-is-mvc">What Is MVC?</a></li>
<li><a href="#what-is-backbone.js">What is Backbone.js?</a></li>
<li><a href="#when-do-i-need-a-javascript-mvc-framework">When Do I Need A JavaScript MVC Framework?</a></li>
<li><a href="#why-consider-backbone.js">Why Consider Backbone.js?</a></li>
<li><a href="#setting-expectations">Setting Expectations</a></li>
</ul></li>
<li><a href="#fundamentals">Fundamentals</a><ul>
<li><a href="#mvc">MVC</a><ul>
<li><a href="#smalltalk-80-mvc">Smalltalk-80 MVC</a></li>
<li><a href="#mvc-applied-to-the-web">MVC Applied To The Web</a></li>
<li><a href="#mvc-in-the-browser">MVC In The Browser</a></li>
<li><a href="#client-side-mvc---backbone-style">Client-Side MVC - Backbone Style</a></li>
<li><a href="#implementation-specifics">Implementation Specifics</a><ul>
<li><a href="#models">Models</a></li>
<li><a href="#views">Views</a></li>
<li><a href="#controllers">Controllers</a></li>
</ul></li>
</ul></li>
<li><a href="#what-does-mvc-give-us">What does MVC give us?</a><ul>
<li><a href="#delving-deeper-into-mvc">Delving Deeper into MVC</a></li>
<li><a href="#summary">Summary</a></li>
<li><a href="#further-reading">Further reading</a></li>
</ul></li>
<li><a href="#fast-facts">Fast facts</a><ul>
<li><a href="#backbone.js">Backbone.js</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-basics">Backbone Basics</a><ul>
<li><a href="#models-1">Models</a><ul>
<li><a href="#initialization">Initialization</a></li>
<li><a href="#getters-setters">Getters & Setters</a></li>
<li><a href="#listening-for-changes-to-your-model">Listening for changes to your model</a></li>
<li><a href="#validation">Validation</a></li>
</ul></li>
<li><a href="#views-1">Views</a><ul>
<li><a href="#creating-new-views">Creating new views</a></li>
<li><a href="#what-is-el">What is <code>el</code>?</a></li>
</ul></li>
<li><a href="#collections">Collections</a><ul>
<li><a href="#restful-persistence">RESTful Persistence</a></li>
<li><a href="#underscore-utility-functions">Underscore utility functions</a></li>
<li><a href="#chainable-api">Chainable API</a></li>
</ul></li>
<li><a href="#events">Events</a><ul>
<li><a href="#on-off-and-trigger">on(), off(), and trigger()</a></li>
<li><a href="#listento-and-stoplistening">listenTo() and stopListening()</a></li>
<li><a href="#events-and-views">Events and Views</a></li>
</ul></li>
<li><a href="#routers">Routers</a><ul>
<li><a href="#backbone.history">Backbone.history</a></li>
</ul></li>
<li><a href="#backbones-sync-api">Backbone’s Sync API</a></li>
<li><a href="#dependencies">Dependencies</a></li>
<li><a href="#summary-1">Summary</a></li>
</ul></li>
<li><a href="#exercise-1-todos---your-first-backbone.js-app">Exercise 1: Todos - Your First Backbone.js App</a><ul>
<li><a href="#static-html">Static HTML</a><ul>
<li><a href="#header-and-scripts">Header and Scripts</a></li>
<li><a href="#application-html">Application HTML</a></li>
<li><a href="#templates">Templates</a></li>
</ul></li>
<li><a href="#todo-model">Todo model</a></li>
<li><a href="#todo-collection">Todo collection</a></li>
<li><a href="#application-view">Application View</a></li>
<li><a href="#individual-todo-view">Individual Todo View</a></li>
<li><a href="#startup">Startup</a></li>
<li><a href="#in-action">In action</a></li>
<li><a href="#completing-deleting-todos">Completing & deleting todos</a></li>
<li><a href="#todo-routing">Todo routing</a></li>
<li><a href="#summary-2">Summary</a></li>
</ul></li>
<li><a href="#exercise-2-book-library---your-first-restful-backbone.js-app">Exercise 2: Book Library - Your first RESTful Backbone.js app</a><ul>
<li><a href="#setting-up">Setting up</a></li>
<li><a href="#wiring-in-the-interface">Wiring in the interface</a><ul>
<li><a href="#adding-models">Adding models</a></li>
<li><a href="#removing-models">Removing models</a></li>
</ul></li>
<li><a href="#creating-the-back-end">Creating the back-end</a><ul>
<li><a href="#install-node.js-npm-and-mongodb">Install node.js, npm and MongoDB</a></li>
<li><a href="#install-node-modules">Install node modules</a></li>
<li><a href="#create-a-simple-web-server">Create a simple web server</a></li>
<li><a href="#connect-to-database">Connect to database</a></li>
</ul></li>
<li><a href="#talking-to-the-server">Talking to the server</a><ul>
<li><a href="#connecting-with-a-third-party-api">Connecting with a third party API</a></li>
<li><a href="#summary-3">Summary</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-extensions">Backbone Extensions</a><ul>
<li><a href="#backbone.marionette">Backbone.Marionette</a><ul>
<li><a href="#boilerplate-rendering-code">Boilerplate Rendering Code</a></li>
<li><a href="#reducing-boilerplate-with-marionette.itemview">Reducing Boilerplate With Marionette.ItemView</a></li>
<li><a href="#memory-management">Memory Management</a></li>
<li><a href="#region-management">Region Management</a></li>
<li><a href="#marionette-todo-app">Marionette Todo app</a><ul>
<li><a href="#controllers-1">Controllers</a></li>
<li><a href="#compositeview">CompositeView</a></li>
</ul></li>
<li><a href="#is-the-marionette-implementation-of-the-todo-app-more-maintainable">Is the Marionette implementation of the Todo app more maintainable?</a></li>
<li><a href="#marionette-and-flexibility">Marionette And Flexibility</a></li>
<li><a href="#and-so-much-more">And So Much More</a></li>
</ul></li>
<li><a href="#thorax">Thorax</a><ul>
<li><a href="#hello-world">Hello World</a></li>
<li><a href="#embedding-child-views">Embedding child views</a></li>
<li><a href="#view-helpers">View helpers</a></li>
<li><a href="#collection-helper">collection helper</a></li>
<li><a href="#custom-html-data-attributes">Custom HTML data attributes</a></li>
<li><a href="#thorax-resources">Thorax Resources</a></li>
</ul></li>
</ul></li>
<li><a href="#common-problems-solutions">Common Problems & Solutions</a><ul>
<li><a href="#view-nesting">View Nesting</a></li>
<li><a href="#what-is-the-best-way-to-manage-models-in-nested-views">What is the best way to manage models in nested Views?</a></li>
<li><a href="#rendering-parent-view-from-child">Rendering Parent View from Child</a></li>
<li><a href="#triggering-updates-in-other-views">Triggering updates in other Views</a></li>
<li><a href="#disposing-views-cleanly">Disposing Views cleanly</a></li>
<li><a href="#disposing-view-hierarchies">Disposing View hierarchies</a></li>
<li><a href="#rendering-view-hierarchies">Rendering View hierarchies</a></li>
<li><a href="#better-model-property-validation">Better Model Property Validation</a></li>
<li><a href="#multiple-backbone-versions">Multiple Backbone versions</a></li>
<li><a href="#building-model-and-view-hierarchies">Building Model and View hierarchies</a></li>
</ul></li>
<li><a href="#modular-development">Modular Development</a><ul>
<li><a href="#introduction-1">Introduction</a></li>
<li><a href="#organizing-modules-with-requirejs-and-amd">Organizing modules with RequireJS and AMD</a><ul>
<li><a href="#maintainability-problems-with-multiple-script-files">Maintainability problems with multiple script files</a></li>
<li><a href="#need-for-better-dependency-management">Need for better dependency management</a></li>
<li><a href="#asynchronous-module-definition-amd">Asynchronous Module Definition (AMD)</a></li>
<li><a href="#writing-amd-modules-with-requirejs">Writing AMD modules with RequireJS</a><ul>
<li><a href="#alternate-syntax">Alternate syntax</a></li>
</ul></li>
<li><a href="#getting-started-with-requirejs">Getting Started with RequireJS</a><ul>
<li><a href="#requirejs-configuration">RequireJS Configuration</a><ul>
<li><a href="#requirejs-shims">RequireJS Shims</a></li>
</ul></li>
<li><a href="#custom-paths">Custom Paths</a></li>
</ul></li>
<li><a href="#require.js-and-backbone-examples">Require.js and Backbone Examples</a><ul>
<li><a href="#wrapping-modules-views-and-other-components-with-amd">Wrapping modules, views and other components with AMD</a></li>
</ul></li>
<li><a href="#keeping-your-templates-external-using-requirejs-and-the-text-plugin">Keeping Your Templates External Using RequireJS And The Text Plugin</a></li>
<li><a href="#optimizing-backbone-apps-for-production-with-the-requirejs-optimizer">Optimizing Backbone apps for production with the RequireJS Optimizer</a></li>
</ul></li>
<li><a href="#optimize-and-build-a-backbone.js-javascript-application-with-requirejs-using-packages">Optimize and Build a Backbone.js JavaScript application with RequireJS using Packages</a><ul>
<li><a href="#file-organization">File organization</a></li>
<li><a href="#build-profile-to-optimize-modular-dependencies-with-code-organized-in-packages">Build profile to optimize modular dependencies with code organized in packages</a></li>
<li><a href="#a-quick-note-on-code-standards">A quick note on code standards</a></li>
<li><a href="#common-pitfall-when-organizing-code-in-modules">Common Pitfall when organizing code in modules</a></li>
<li><a href="#executing-the-build-with-r.js">Executing the Build with r.js</a></li>
</ul></li>
<li><a href="#exercise-building-a-modular-backbone-app-with-amd-requirejs">Exercise: Building a modular Backbone app with AMD & RequireJS</a><ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#markup">Markup</a></li>
<li><a href="#configuration-options">Configuration options</a></li>
<li><a href="#modularizing-our-models-views-and-collections">Modularizing our models, views and collections</a></li>
</ul></li>
<li><a href="#route-based-module-loading">Route based module loading</a><ul>
<li><a href="#json-based-module-configuration">JSON based module configuration</a></li>
<li><a href="#module-loader-router">Module loader Router</a></li>
<li><a href="#using-nodejs-to-handle-pushstate">Using NodeJS to handle pushState</a></li>
</ul></li>
<li><a href="#decoupling-backbone-with-the-mediator-and-facade-patterns">Decoupling Backbone with the Mediator and Facade Patterns</a><ul>
<li><a href="#summary-4">Summary</a></li>
<li><a href="#exercise">Exercise</a></li>
</ul></li>
<li><a href="#paginating-backbone.js-requests-collections">Paginating Backbone.js Requests & Collections</a><ul>
<li><a href="#paginators-pieces">Paginator’s pieces</a></li>
<li><a href="#live-examples">Live Examples</a></li>
<li><a href="#paginator.requestpager">Paginator.requestPager</a><ul>
<li><a href="#create-a-new-paginated-collection">1. Create a new Paginated collection</a></li>
<li><a href="#set-the-model-for-the-collection-as-normal">2: Set the model for the collection as normal</a></li>
<li><a href="#configure-the-base-url-and-the-type-of-the-request">3. Configure the base URL and the type of the request</a></li>
<li><a href="#configure-how-the-library-will-show-the-results">4. Configure how the library will show the results</a></li>
<li><a href="#configure-the-parameters-we-want-to-send-to-the-server">5. Configure the parameters we want to send to the server</a></li>
<li><a href="#finally-configure-collection.parse-and-were-done">6. Finally, configure Collection.parse() and we’re done</a></li>
<li><a href="#convenience-methods">Convenience methods:</a></li>
</ul></li>
<li><a href="#paginator.clientpager">Paginator.clientPager</a><ul>
<li><a href="#create-a-new-paginated-collection-with-a-model-and-url">1. Create a new paginated collection with a model and URL</a></li>
<li><a href="#configure-the-base-url-and-the-type-of-the-request-1">2. Configure the base URL and the type of the request</a></li>
<li><a href="#configure-how-the-library-will-show-the-results-1">3. Configure how the library will show the results</a></li>
<li><a href="#configure-the-parameters-we-want-to-send-to-the-server-1">4. Configure the parameters we want to send to the server</a></li>
<li><a href="#finally-configure-collection.parse-and-were-done-1">5. Finally, configure Collection.parse() and we’re done</a></li>
<li><a href="#convenience-methods-1">Convenience methods:</a></li>
<li><a href="#implementation-notes">Implementation notes:</a></li>
</ul></li>
<li><a href="#plugins">Plugins</a></li>
</ul></li>
<li><a href="#thorax-1"><a name="thorax">Thorax</a></a><ul>
<li><a href="#view-helper">view helper</a></li>
<li><a href="#creating-new-view-helpers">Creating new View helpers</a></li>
</ul></li>
</ul></li>
<li><a href="#backbone-boilerplate-and-grunt-bbb">Backbone Boilerplate And Grunt-BBB</a><ul>
<li><a href="#getting-started">Getting Started</a><ul>
<li><a href="#backbone-boilerplate-and-grunt-bbb-1">Backbone Boilerplate and Grunt-BBB</a></li>
</ul></li>
<li><a href="#creating-a-new-project">Creating a new project</a><ul>
<li><a href="#index.html">index.html</a></li>
<li><a href="#config.js">config.js</a></li>
<li><a href="#main.js">main.js</a></li>
<li><a href="#app.js">app.js</a></li>
<li><a href="#creating-backbone-boilerplate-modules">Creating Backbone Boilerplate Modules</a></li>
<li><a href="#router.js">router.js</a></li>
</ul></li>
<li><a href="#related-tools-projects">Related Tools & Projects</a></li>
<li><a href="#conclusions">Conclusions</a></li>
</ul></li>
<li><a href="#mobile-applications">Mobile Applications</a><ul>
<li><a href="#backbone-jquery-mobile">Backbone & jQuery Mobile</a><ul>
<li><a href="#resolving-the-routing-conflicts">Resolving the routing conflicts</a></li>
<li><a href="#exercise-a-backbone-require.jsamd-app-with-jquery-mobile">Exercise: A Backbone, Require.js/AMD app with jQuery Mobile</a></li>
<li><a href="#getting-started-1">Getting started</a></li>
<li><a href="#jquery-mobile-going-beyond-mobile-application-development">jQuery Mobile: Going beyond mobile application development</a></li>
</ul></li>
</ul></li>
<li><a href="#unit-testing">Unit Testing</a></li>
<li><a href="#jasmine">Jasmine</a><ul>
<li><a href="#introduction-2">Introduction</a></li>
<li><a href="#suites-specs-spies">Suites, Specs & Spies</a></li>
<li><a href="#beforeeach-and-aftereach">beforeEach and afterEach()</a></li>
<li><a href="#shared-scope">Shared scope</a></li>
<li><a href="#getting-setup">Getting setup</a></li>
<li><a href="#tdd-with-backbone">TDD With Backbone</a></li>
<li><a href="#models-2">Models</a></li>
<li><a href="#collections-1">Collections</a></li>
<li><a href="#views-2">Views</a></li>
<li><a href="#initial-setup">Initial setup</a></li>
<li><a href="#view-rendering">View rendering</a></li>
<li><a href="#rendering-with-a-templating-system">Rendering with a templating system</a></li>
<li><a href="#conclusions-1">Conclusions</a></li>
<li><a href="#exercise-1">Exercise</a></li>
<li><a href="#further-reading-1">Further reading</a></li>
<li><a href="#unit-testing-backbone-applications-with-qunit-and-sinonjs">Unit Testing Backbone Applications With QUnit And SinonJS</a></li>
<li><a href="#introduction-3">Introduction</a></li>
</ul></li>
<li><a href="#qunit">QUnit</a><ul>
<li><a href="#getting-setup-1">Getting Setup</a><ul>
<li><a href="#sample-html-with-qunit-compatible-markup">Sample HTML with QUnit-compatible markup:</a></li>
</ul></li>
<li><a href="#assertions">Assertions</a><ul>
<li><a href="#basic-test-case-using-test-name-callback">Basic test case using test( name, callback ):</a></li>
<li><a href="#comparing-the-actual-output-of-a-function-against-the-expected-output">Comparing the actual output of a function against the expected output:</a></li>
</ul></li>
<li><a href="#adding-structure-to-assertions">Adding structure to assertions</a><ul>
<li><a href="#basic-qunit-modules">Basic QUnit Modules:</a></li>
<li><a href="#using-setup-and-teardown">Using setup() and teardown() :</a></li>
<li><a href="#using-setup-and-teardown-for-instantiation-and-clean-up">Using setup() and teardown() for instantiation and clean-up:</a></li>
</ul></li>
<li><a href="#assertion-examples">Assertion examples</a><ul>
<li><a href="#equal---a-comparison-assertion.-it-passes-if-actual-expected">equal - a comparison assertion. It passes if actual == expected</a></li>
<li><a href="#notequal---a-comparison-assertion.-it-passes-if-actual-expected">notEqual - a comparison assertion. It passes if actual != expected</a></li>
<li><a href="#strictequal---a-comparison-assertion.-it-passes-if-actual-expected.">strictEqual - a comparison assertion. It passes if actual === expected.</a></li>
<li><a href="#notstrictequal---a-comparison-assertion.-it-passes-if-actual-expected.">notStrictEqual - a comparison assertion. It passes if actual !== expected.</a></li>
<li><a href="#deepequal---a-recursive-comparison-assertion.-unlike-strictequal-it-works-on-objects-arrays-and-primitives.">deepEqual - a recursive comparison assertion. Unlike strictEqual(), it works on objects, arrays and primitives.</a></li>
<li><a href="#notdeepequal---a-comparison-assertion.-this-returns-the-opposite-of-deepequal">notDeepEqual - a comparison assertion. This returns the opposite of deepEqual</a></li>
<li><a href="#raises---an-assertion-which-tests-if-a-callback-throws-any-exceptions">raises - an assertion which tests if a callback throws any exceptions</a></li>
</ul></li>
<li><a href="#fixtures">Fixtures</a><ul>
<li><a href="#fixture-markup">Fixture markup:</a></li>
<li><a href="#fixtures-example">Fixtures example:</a></li>
</ul></li>
<li><a href="#asynchronous-code">Asynchronous code</a></li>
</ul></li>
<li><a href="#sinonjs">SinonJS</a><ul>
<li><a href="#what-is-sinonjs">What is SinonJS?</a><ul>
<li><a href="#basic-spies">Basic Spies:</a></li>
<li><a href="#spying-on-existing-functions">Spying On Existing Functions:</a></li>
<li><a href="#matching-arguments-test-a-spy-was-called-with-a-specific-set-of-arguments">Matching arguments: test a spy was called with a specific set of arguments:</a></li>
<li><a href="#stricter-argument-matching-test-a-spy-was-called-at-least-once-with-specific-arguments-and-no-others">Stricter argument matching: test a spy was called at least once with specific arguments and no others:</a></li>
<li><a href="#testing-call-order-testing-if-a-spy-was-called-before-or-after-another-spy">Testing call order: testing if a spy was called before or after another spy:</a></li>
<li><a href="#match-execution-counts-test-a-spy-was-called-a-specific-number-of-times">Match execution counts: test a spy was called a specific number of times:</a></li>
</ul></li>
<li><a href="#stubs-and-mocks">Stubs and mocks</a><ul>
<li><a href="#stubs">Stubs</a></li>
<li><a href="#mocks">Mocks</a></li>
</ul></li>
<li><a href="#exercise-2">Exercise</a><ul>
<li><a href="#models-3">Models</a></li>
<li><a href="#collections-2">Collections</a></li>
<li><a href="#views-3">Views</a></li>
<li><a href="#event">Event</a></li>
<li><a href="#app">App</a></li>
</ul></li>
<li><a href="#further-reading-resources">Further Reading & Resources</a></li>
</ul></li>
<li><a href="#resources">Resources</a><ul>
<li><a href="#books-courses">Books & Courses</a></li>
<li><a href="#extensionslibraries">Extensions/Libraries</a></li>
</ul></li>
<li><a href="#conclusions-2">Conclusions</a><ul>
<li><a href="#notes">Notes</a></li>
</ul></li>
<li><a href="#appendix">Appendix</a><ul>
<li><a href="#a-simple-javascript-mvc-implementation">A Simple JavaScript MVC Implementation</a><ul>
<li><a href="#event-system">Event System</a></li>
<li><a href="#models-4">Models</a></li>
<li><a href="#views-4">Views</a></li>
<li><a href="#controllers-2">Controllers</a></li>
<li><a href="#practical-usage">Practical Usage</a></li>
</ul></li>
<li><a href="#mvp">MVP</a><ul>
<li><a href="#models-views-presenters">Models, Views & Presenters</a></li>
</ul></li>
<li><a href="#mvp-or-mvc">MVP or MVC?</a></li>
<li><a href="#mvc-mvp-and-backbone.js">MVC, MVP and Backbone.js</a></li>
<li><a href="#namespacing">Namespacing</a><ul>
<li><a href="#what-is-namespacing">What is namespacing?</a></li>
</ul></li>
<li><a href="#backbone-dependency-details">Backbone Dependency Details</a><ul>
<li><a href="#dom-manipulation">DOM Manipulation</a></li>
<li><a href="#utilities">Utilities</a></li>
<li><a href="#restful-persistence-1">RESTful persistence</a></li>
<li><a href="#routing">Routing</a></li>
</ul></li>
<li><a href="#upgrading-to-backbone-0.9.10">Upgrading to Backbone 0.9.10</a><ul>
<li><a href="#model">Model</a></li>
<li><a href="#collection">Collection</a></li>
<li><a href="#view">View</a></li>
<li><a href="#events-1">Events</a></li>
<li><a href="#routers-1">Routers</a></li>
<li><a href="#sync">Sync</a></li>
<li><a href="#other">Other</a></li>
</ul></li>
</ul></li>
</ul>
</nav>
<h2 id="prelude"><a href="#TOC">Prelude</a></h2>
<figure>
<img src="img/logo.jpg"><figcaption></figcaption>
</figure>
<p>How do you write an organized, maintainable application with JavaScript? This book helps you answer this question with a walkthrough of the <a href="http://documentcloud.github.com/backbone/">Backbone.js</a> library for structuring web applications.</p>
<p>Begin with the fundamentals, work your way through the internals, practicals and finally learn how to build on top of what Backbone.js has to offer. If you are a developer looking to write code that can be more easily read, structured and extended - this guide is ideal for you.</p>
<p>This (in-progress) book is released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">license</a> meaning you can both grab a copy of the book for free or help to further <a href="https://github.com/addyosmani/backbone-fundamentals/">improve</a> it.</p>
<p>I’m very pleased to announce that this book will be out in physical form (once complete) via <a href="http://shop.oreilly.com/product/0636920025344.do">O’Reilly Media</a>. 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.</p>
<p>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.</p>
<p>My extended thanks go out to <a href="https://github.com/jashkenas">Jeremy Ashkenas</a> for creating Backbone.js and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">these</a> members of the community for their assistance tweaking this project.</p>
<p>I hope you find this book helpful!</p>
<h2 id="target-audience"><a href="#TOC">Target Audience</a></h2>
<p>This book is targeted at novice to intermediate developers wishing to learn how to better structure their client-side code. An understanding of JavaScript fundamentals is required to get the most out of it, however we have tried to provide a basic description of these concepts where possible.</p>
<h2 id="acknowledgements"><a href="#TOC">Acknowledgements</a></h2>
<p>I am indebted to the fantastic work done by the technical reviewers who helped improve this book. Their knowledge, energy and passion have helped shape it into a better learning resource and they continue to serve as a source of inspiration. Thanks go out to:</p>
<ul>
<li><a href="http://github.com/dcmaf">Marc Friedman</a></li>
<li><a href="http://github.com/wibblymat">Mat Scales</a></li>
<li><a href="http://github.com/g6scheme">Dusan Gledovic</a></li>
<li><a href="http://github.com/sindresorhus">Sindre Sorhus</a></li>
</ul>
<h2 id="credits"><a href="#TOC">Credits</a></h2>
<p>None of this would have been possible without the time and effort invested by the other developers and authors in the community who contributed to it. I would like to extend my thanks to Derick Bailey, Ryan Eastridge, Jack Franklin, Mike Ball, Uģis Ozols, Björn Ekengren and <a href="https://github.com/addyosmani/backbone-fundamentals/graphs/contributors">everyone else</a> that helped made this project happen.</p>
<h2 id="reading"><a href="#TOC">Reading</a></h2>
<p>I assume your level of knowledge about JavaScript goes beyond the basics and as such certain topics such as object literals are skipped. If you need to learn more about the language, I am happy to suggest:</p>
<ul>
<li><a href="http://www.amazon.com/Object-Oriented-Javascript-Stoyan-Stefanov/dp/1847194141">Object-Oriented JavaScript</a> by Stoyan Stefanov (Packt Publishing)</li>
<li><a href="http://shop.oreilly.com/product/9780596805531.do">JavaScript: The Definitive Guide</a> by David Flanagan (O’Reilly)</li>
<li><a href="http://shop.oreilly.com/product/9780596517748.do">JavaScript: The Good Parts</a> by Douglas Crockford (O’Reilly)</li>
<li><a href="http://www.informit.com/store/effective-javascript-68-specific-ways-to-harness-the-9780321812186">Effective JavaScript</a> by David Herman (Pearson)</li>
</ul>
<h1 id="introduction"><a href="#TOC">Introduction</a></h1>
<p>Frank Lloyd Wright once said <q>You can’t make an architect. You can however open the doors and windows toward the light as you see it.</q> In this book, I hope to shed some light on how to improve the structure of your web applications, opening doors to what will hopefully be more maintainable, readable applications in your future.</p>
<p>The goal of all architecture is to build something well; in our case, to craft code that is enduring and delights both ourselves and the developers who will maintain our code long after we are gone. We all want our architecture to be simple, yet beautiful.</p>
<p>When writing a web application from scratch it can be easy to feel like you can get by simply relying on a DOM manipulation library (such as jQuery) and a handful of plugins. The challenge with this approach is that it doesn’t take long to get lost in a nested pile of callbacks and DOM elements without any real structure in place.</p>
<p>In short, you can end up with a pile of spaghetti code - code that is disorganized and difficult to follow. This type of code has no simple panacea, short of a rewrite that may end up costing both time and money to complete. Fortunately, there are ways to avoid this problem.</p>
<p>Modern JavaScript frameworks and libraries can bring structure and organization to your projects, establishing a maintainable foundation right from the start. They build on the trials and tribulations of developers who have had to work around callback chaos similar to that which you are facing now or may in the near future.</p>
<p>In <q>Developing Backbone.js Applications,</q> I and a number of other experienced authors will show you how to improve your web application structure using one such library - Backbone.js.</p>
<h3 id="what-is-mvc"><a href="#TOC">What Is MVC?</a></h3>
<p>A number of modern JavaScript frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application into three parts:</p>
<ul>
<li>Models represent the domain-specific knowledge and data in an application. Think of this as being a <q>type</q> of data you can model — like a User, Photo, or Todo note. Models can notify observers when their state changes.</li>
<li>Views typically constitute the user interface in an application (e.g., markup and templates), but don’t have to be. They observe Models, but don’t directly communicate with them.</li>
<li>Controllers handle input (e.g., clicks, user actions) and update Models.</li>
</ul>
<p>Thus, in an MVC application, user input is acted upon by Controllers which update Models. Views observe Models and update the user interface when changes occur.</p>
<p>JavaScript MVC frameworks don’t always strictly follow the above pattern. Some solutions (including Backbone.js) merge the responsibility of the Controller into the View, while other approaches add additional components into the mix.</p>
<p>For this reason we refer to such frameworks as following the MV* pattern; that is, you’re likely to have a Model and a View, but a distinct Controller might not be present and other components may come into play.</p>
<h3 id="what-is-backbone.js"><a href="#TOC">What is Backbone.js?</a></h3>
<figure>
<img src="img/backbonejsorg.jpg"><figcaption></figcaption>
</figure>
<p>Backbone.js is a lightweight JavaScript library that adds structure to your client-side code. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.</p>
<p>Developers commonly use libraries like Backbone.js to create single-page applications (SPAs). SPAs are web applications that load into the browser and then react to data changes on the client side without requiring complete page refreshes from the server. Backbone.js is a mature, popular library at the time of writing and has both a large development community online as well as a wealth of plugins and extensions available that build upon it. It has been used to create non-trivial applications by companies such as Disqus, Walmart, SoundCloud and Foursquare.</p>
<h3 id="when-do-i-need-a-javascript-mvc-framework"><a href="#TOC">When Do I Need A JavaScript MVC Framework?</a></h3>
<p>When building a single-page application using JavaScript, whether it involves a complex user interface or is simply trying to reduce the number of HTTP requests required for new Views, you will likely find yourself inventing many of the pieces that make up an MV* framework.</p>
<p>At the outset, it isn’t terribly difficult to write your own application framework that offers some opinionated way to avoid spaghetti code; however, to say that it is equally as trivial to write something as robust as Backbone would be a grossly incorrect assumption.</p>
<p>There’s a lot more that goes into structuring an application than tying together a DOM manipulation library, templating, and routing. Mature MV* frameworks typically include not only the pieces you would find yourself writing, but also include solutions to problems you’ll find yourself running into later on down the road. This is a time-saver that you shouldn’t underestimate the value of.</p>
<p>So, where will you likely need an MV* framework and where won’t you?</p>
<p>If you’re writing an application where much of the heavy lifting for view rendering and data manipulation will be occurring in the browser, you may find a JavaScript MV* framework useful. Examples of applications that fall into this category are GMail and Google Docs.</p>
<p>These types of applications typically download a single payload containing all the scripts, stylesheets, and markup users need for common tasks and then perform a lot of additional behavior in the background. For instance, it’s trivial to switch between reading an email or document to writing one without sending a new page request to the server.</p>
<p>If, however, you’re building an application that still relies on the server for most of the heavy-lifting of page/view rendering and you’re just using a little JavaScript or jQuery to make things more interactive, an MV* framework may be overkill. There certainly are complex Web applications where the partial rendering of views can be coupled with a single-page application effectively, but for everything else, you may find yourself better sticking to a simpler setup.</p>
<p>Maturity in software (framework) development isn’t simply about how long a framework has been around. It’s about how solid the framework is and more importantly how well it’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?</p>
<h3 id="why-consider-backbone.js"><a href="#TOC">Why Consider Backbone.js?</a></h3>
<p>Does the following describe you?:</p>
<p><q>I want a flexible library which allows me to cleanly separate concerns in my application. It should support a persistence layer and RESTful sync, models, views, event-driven communication and routing. I’d like some decisions about the architecture left up to me.</q></p>
<p>As I may be building something complex, I’d like there to be an active extension community around the framework that is already addressing issues I may run into down the road. Ideally, there are also scaffolding tools available for the solution."</p>
<p>If so, continue reading.</p>
<p>Backbone’s main benefits, regardless of your target platform or device, include helping:</p>
<ul>
<li>Organize the structure to your application</li>
<li>Simplify server-side persistence</li>
<li>Decouple the DOM from your page’s data</li>
<li>Model data, views, and routers in a succinct manner</li>
<li>Provide DOM, model, and collection synchronization</li>
</ul>
<h3 id="setting-expectations"><a href="#TOC">Setting Expectations</a></h3>
<p>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 an issue (or better yet, a pull-request) on the book’s <a href="https://github.com/addyosmani/backbone-fundamentals">GitHub site</a>. It won’t take long and you’ll be helping other developers avoid the problems you ran into.</p>
<p>Topics will include MVC theory and how to build applications using Backbone’s Models, Views, Collections, and Routers. I’ll also be taking you through advanced topics like modular development with Backbone.js and AMD (via RequireJS), solutions to common problems like nested views, how to solve routing problems with Backbone and jQuery Mobile, and much more.</p>
<p>Here is a peek at what you will be learning in each chapter:</p>
<p><i>Chapter 2, Fundamentals</i> traces the history of the MVC design pattern and introduces how it is implemented by Backbone.js and other JavaScript frameworks.</p>
<p><i>Chapter 3, Backbone Basics</i> covers the major features of the core Backbone.js framework and technologies and techniques you will need to know in order to apply it.</p>
<p><i>Chapter 4, Exercise 1: Todos - Your First Backbone.js App</i> takes you step-by-step through development of a simple client-side Todo List application.</p>
<p><i>Chapter 5, Exercise 2: Book Library - Your First RESTful Backbone.js App</i> walks you through development of a Book Library application which persists its model to a server using a REST API.</p>
<p><i>Chapter 6, Backbone Boilerplate And Grunt BBB</i> introduces powerful tools you can use to bootstrap a new Backbone.js application with boilerplate code.</p>
<p><i>Chapter 7, Common Problems and Solutions</i> reviews common issues you may encounter when using Backbone.js and ways of addressing them.</p>
<p><i>Chapter 8, Backbone Extensions</i> describes Backbone.Marionette and Thorax, two extension frameworks which add features to Backbone.js that are useful for developing large-scale applications.</p>
<p><i>Chapter 9, Modular Development</i> looks at how AMD modules and RequireJS can be used to modularize your code.</p>
<p><i>Chapter 10, Mobile Applications</i> addresses the issues that arise when using Backbone with jQuery Mobile.</p>
<p><i>Chapter 11, Unit Testing</i> covers how to unit test Backbone code using the Jasmine test framework.</p>
<p><i>Chapter 12, Unit Testing Backbone Applications with QUnit and SinonJS</i> discusses how to use the QUnit and SinusJS frameworks for unit testing.</p>
<p><i>Chapter 13, Resources</i> provides references to additional Backbone-related resources.</p>
<p><i>Chapter 14, Conclusions</i> wraps up the our tour through the world of Backbone.js development.</p>
<p><i>Chapter 15, Appendix</i> returns to our design pattern discussion by contrasting MVC with the Model-View-Presenter (MVP) pattern and examines how Backbone.js relates to the two patterns. It also provides useful information for existing Backbone users who may be upgrading from Backbone 0.9.2 to version 0.9.10 and beyond.</p>
<h1 id="fundamentals"><a href="#TOC">Fundamentals</a></h1>
<p>Design patterns are proven solutions to common development problems that can help us improve the organization and structure of our applications. By using patterns, we benefit from the collective experience of skilled developers who have repeatedly solved similar problems.</p>
<p>Historically, developers creating desktop and server-class applications have had a wealth of design patterns available for them to lean on, but it’s only been in the past few years that such patterns have been applied to client-side development.</p>
<p>In this chapter, we’re going to explore the evolution of the Model-View-Controller (MVC) design pattern and get our first look at how the Backbone.js framework allows us to apply this pattern to client-side development.</p>
<h2 id="mvc"><a href="#TOC">MVC</a></h2>
<p>MVC 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 managing logic, user-input, and coordination of Models and Views. The pattern was originally designed by <a href="http://en.wikipedia.org/wiki/Trygve_Reenskaug">Trygve Reenskaug</a> while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in <a href="http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612"><q>Design Patterns: Elements of Reusable Object-Oriented Software</q></a> (The <q>GoF</q> or <q>Gang of Four</q> book) in 1994, which played a role in popularizing its use.</p>
<h3 id="smalltalk-80-mvc"><a href="#TOC">Smalltalk-80 MVC</a></h3>
<p>It’s important to understand the issues that the original MVC pattern was aiming to solve as it has changed quite heavily since the days of its origin. Back in the 70’s, graphical user-interfaces were few and far between. An approach known as <a href="http://martinfowler.com/eaaDev/uiArchs.html">Separated Presentation</a> 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’s screen.</p>
<p>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’s MVC architecture:</p>
<ul>
<li>A Domain element was known as a Model and was ignorant of the user-interface (Views and Controllers)</li>
<li>Presentation was taken care of by the View and the Controller, but there wasn’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</li>
<li>The Controller’s role in this pair was handling user input (such as key-presses and click events) and doing something sensible with them</li>
<li>The Observer pattern was used to update the View whenever the Model changed</li>
</ul>
<p>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’s architecture decades ago. In Smalltalk-80’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 Model should result in the View being refreshed instantly.</p>
<p>Martin Fowler has done an excellent job of writing about the <a href="http://martinfowler.com/eaaDev/uiArchs.html">origins</a> of MVC over the years and if you are interested in further historical information about Smalltalk-80’s MVC, I recommend reading his work.</p>
<h3 id="mvc-applied-to-the-web"><a href="#TOC">MVC Applied To The Web</a></h3>
<p>The web heavily relies on the HTTP protocol, which is stateless. This means that there is not a constantly open connection between the browser and server; each request instantiates a new communication channel between the two. Once the request initiator (e.g., a browser) gets a response the connection is closed. This fact creates a completely different context when compared to the one of the operating systems on which many of the original MVC ideas were developed. The MVC implementation has to conform to the web context.</p>
<p>A typical server-side MVC implementation implements the Front Controller design pattern. This pattern layers an MVC stack behind a single point of entry. This single point of entry means that all HTTP requests (e.g., <code>http://www.example.com</code>, <code>http://www.example.com/whichever-page/</code>, etc.) are routed by the server’s configuration to the same handler, independent of the URI.</p>
<p>When the Front Controller receives an HTTP request it analyzes it and decides which class (Controller) and method (Action) to invoke. The selected Controller Action takes over and interacts with the appropriate Model to fulfill the request. The Controller receives data back from the Model, loads an appropriate View, injects the Model data into it, and returns the response to the browser.</p>
<p>For example, let’s say we have our blog on <code>www.example.com</code> and we want to edit an article (with <code>id=43</code>) and request <code>http://www.example.com/article/edit/43</code>:</p>
<p>On the server side, the Front Controller would analyze the URL and invoke the Article Controller (corresponding to the <code>/article/</code> part of the URI) and its Edit Action (corresponding to the <code>/edit/</code> part of the URI). Within the Action there would be a call to, let’s say, the Articles Model and its <code>Articles::getEntry(43)</code> method (43 corresponding to the <code>/43</code> at the end of the URI). This would return the blog article data from the database for edit. The Article Controller would then load the (<code>article/edit</code>) View which would include logic for injecting the article’s data into a form suitable for editing its content, title, and other (meta) data. Finally, the resulting HTML response would be returned to the browser.</p>
<p>As you can imagine, a similar flow is necessary with POST requests after we press a save button in a form. The POST action URI would look like <code>/article/save/43</code>. The request would go through the same Controller, but this time the Save Action would be invoked (due to the <code>/save/</code> URI chunk), the Articles Model would save the edited article to the database with <code>Articles::saveEntry(43)</code>, and the browser would be redirected to the <code>/article/edit/43</code> URI for further editing.</p>
<p>Finally, if the user requested <code>http://www.example.com/</code> the Front Controller would invoke the default Controller and Action; e.g., the Index Controller and its Index action. Within Index Action there would be a call to the Articles model and its <code>Articles::getLastEntries(10)</code> method which would return the last 10 blog posts. The Controller would load the blog/index View which would have basic logic for listing the blog posts.</p>
<p>The picture below shows this typical HTTP request/response lifecycle for server-side MVC:</p>
<figure>
<img src="img/webmvcflow_bacic.png"><figcaption></figcaption>
</figure>
<p>The Server receives an HTTP request and routes it through a single entry point. At that entry point, the Front Controller analyzes the request and based on it invokes an Action of the appropriate Controller. This process is called routing. The Action Model is asked to return and/or save submitted data. The Model communicates with the data source (e.g., database or API). Once the Model completes its work it returns data to the Controller which then loads the appropriate View. The View executes presentation logic (loops through articles and prints titles, content, etc.) using the supplied data. In the end, an HTTP response is returned to the browser.</p>
<p>The need for fast, complex, and responsive Ajax-powered web applications demands replication of a lot of this logic on the client side, dramatically increasing the size and complexity of the code residing there. Eventually this has brought us to the point where we need MVC (or a similar architecture) implemented on the client side to better structure the code and make it easier to maintain and further extend during the application life-cycle.</p>
<p>And, of course, JavaScript and browsers constitute another context to which the traditional MVC paradigm must be adapted.</p>
<h3 id="mvc-in-the-browser"><a href="#TOC">MVC In The Browser</a></h3>
<p>In complex JavaScript single-page web applications (SPA), all application responses (e.g., UI updates) to user inputs are done seamlessly on the client-side. Data fetching and persistence (e.g., saving to a database on a server) are done with Ajax in the background. For silky, slick, and smooth user experiences, the code powering these interactions needs to be well thought out.</p>
<p><strong>The problem</strong></p>
<p>A typical page in a SPA consists of small elements representing logical entities. These entities belong to specific data domains and need to be presented in particular ways on the page.</p>
<p>A good example is a basket in an e-commerce web application which can have items added to it. This basket might be presented to the user in a box in the top right corner of the page (see the picture below):</p>
<figure>
<img src="img/wireframe_e_commerce.png"><figcaption></figcaption>
</figure>
<p>The basket and its data are presented in HTML. The data and its associated View in HTML changes over time. There was a time when we used jQuery (or a similar DOM manipulation library) and a bunch of Ajax calls and callbacks to keep the two in sync. That often produced code that was not well-structured or easy to maintain. Bugs were frequent and perhaps even unavoidable.</p>
<p>Through evolution, trial and error, and a lot of spaghetti (and not so spaghetti-like) code, JavaScript developers have, in the end, harnessed the ideas of the traditional MVC paradigm. This has led to the development of a number of JavaScript MVC frameworks, including Ember.js, JavaScriptMVC, Angular.js, and of course Backbone.js.</p>
<h3 id="client-side-mvc---backbone-style"><a href="#TOC">Client-Side MVC - Backbone Style</a></h3>
<p>Let’s take our first look at how Backbone.js brings the benefits of MVC to client-side development using a Todo application as our example. We will build on this example in the coming chapters when we explore Backbone’s features but for now we will just focus on the core components’ relationships to MVC.</p>
<p>Our example will need a div element to which we can attach a list of Todo’s. It will also need an HTML template containing a placeholder for a Todo item title and a completion checkbox which can be instantiated for Todo item instances. These are provided by the following HTML:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="er"><</span>!doctype html>
<span class="kw"><html</span><span class="ot"> lang=</span><span class="st">"en"</span><span class="kw">></span>
<span class="kw"><head></span>
<span class="kw"><meta</span><span class="ot"> charset=</span><span class="st">"utf-8"</span><span class="kw">></span>
<span class="kw"><title></title></span>
<span class="kw"><meta</span><span class="ot"> name=</span><span class="st">"description"</span><span class="ot"> content=</span><span class="st">""</span><span class="kw">></span>
<span class="kw"></head></span>
<span class="kw"><body></span>
<span class="kw"><div</span><span class="ot"> id=</span><span class="st">"todo"</span><span class="kw">></span>
<span class="kw"></div></span>
<span class="kw"><script</span><span class="ot"> type=</span><span class="st">"text/template"</span><span class="ot"> id=</span><span class="st">"item-template"</span><span class="kw">></span>
<div>
<input id=<span class="st">"todo</span>_<span class="st">complete"</span> type=<span class="st">"checkbox"</span> <%= completed ? <span class="ch">'checked</span>="<span class="ch">checked</span>"<span class="ch">'</span> : <span class="ch">''</span> %>>
<%- title %>
</div>
<span class="kw"></script></span>
<span class="kw"><script</span><span class="ot"> src=</span><span class="st">"underscore-min.js"</span><span class="kw">></script></span>
<span class="kw"><script</span><span class="ot"> src=</span><span class="st">"backbone-min.js"</span><span class="kw">></script></span>
<span class="kw"><script</span><span class="ot"> src=</span><span class="st">"jquery-min.js"</span><span class="kw">></script></span>
<span class="kw"><script</span><span class="ot"> src=</span><span class="st">"example.js"</span><span class="kw">></script></span>
<span class="kw"></body></span>
<span class="kw"></html></span></code></pre>
<p>In our Todo application, Backbone Model instances are used to hold the data for each Todo item:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Define a Todo Model</span>
<span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Instantiate the Todo Model with a title, allowing completed attribute</span>
<span class="co">// to default to false</span>
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">'Check attributes property of the logged models in the console.'</span>
});</code></pre>
<p>Our Todo Model extends Backbone.Model and simply defines default values for two data attributes. As you will discover in the upcoming chapters, Backbone Models provide many more features but this simple Model illustrates that first and foremost a Model is a data container.</p>
<p>Each Todo instance will be rendered on the page by a TodoView:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="ch">'li'</span>,
<span class="co">// Cache the template function for a single item.</span>
<span class="dt">todoTpl</span>: <span class="kw">_</span>.<span class="fu">template</span>( $(<span class="ch">'#item-template'</span>).<span class="fu">html</span>() ),
<span class="dt">events</span>: {
<span class="ch">'dblclick label'</span>: <span class="ch">'edit'</span>,
<span class="ch">'keypress .edit'</span>: <span class="ch">'updateOnEnter'</span>,
<span class="ch">'blur .edit'</span>: <span class="ch">'close'</span>
},
<span class="co">// Re-render the titles of the todo item.</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">todoTpl</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">'.edit'</span>);
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="dt">edit</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo label is double clicked</span>
},
<span class="dt">close</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo loses focus</span>
},
<span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
<span class="co">// executed on each keypress when in todo edit mode, </span>
<span class="co">// but we'll wait for enter to get in action</span>
}
});
<span class="co">// create a view for a todo</span>
<span class="kw">var</span> todoView = <span class="kw">new</span> TodoView({<span class="dt">model</span>: todo});</code></pre>
<p>TodoView is defined by extending Backbone.View and is instantiated with an associated Model. In our example, the <code>render()</code> method uses a template to construct the HTML for the Todo item which is placed inside a li element. Each call to <code>render()</code> will replace the content of the li element using the current Model data. Thus, a View instance renders the content of a DOM element using the attributes of an associated Model. Later we will see how a View can bind its <code>render()</code> method to Model change events, causing the View to re-render whenever the Model changes.</p>
<p>So far, we have seen that Backbone.Model implements the Model aspect of MVC and Backbone.View implements the View. However, as we noted earlier, Backbone departs from traditional MVC when it comes to Controllers - there is no Backbone.Controller!</p>
<p>Instead, the Controller responsibility is addressed within the View. Recall that Controllers respond to requests and perform appropriate actions which may result in changes to the Model and updates to the View. In a single-page application, rather than having requests in the traditional sense, we have events. Events can be traditional browser DOM events (e.g., clicks) or internal application events such as Model changes.</p>
<p>In our TodoView, the <code>events</code> attribute fulfills the role of the Controller configuration, defining how events occurring within the View’s DOM element are to be routed to event-handling methods defined in the View.</p>
<p>While in this instance events help us relate Backbone to the MVC pattern, we will see them playing a much larger role in our SPA applications. Backbone.Event is a fundamental Backbone component which is mixed into both Backbone.Model and Backbone.View, providing them with rich event management capabilities.</p>
<p>This completes our first encounter with Backbone.js. The remainder of this book will explore the many features of the framework which build on these simple constructs. Before moving on, let’s take a look at common features of JavaScript MV* frameworks.</p>
<h3 id="implementation-specifics"><a href="#TOC">Implementation Specifics</a></h3>
<h4 id="models"><a href="#TOC">Models</a></h4>
<ul>
<li><p>The built-in capabilities of Models vary across frameworks; however, it’s common for them to support validation of attributes, where attributes represent the properties of the Model, such as a Model identifier.</p></li>
<li><p>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’s localStorage data-store or synchronized with a database.</p></li>
<li><p>A Model may also have single or multiple Views observing it. Depending on the requirements, a developer might create a single View displaying all Model attributes, or they might create separate Views displaying different attributes. The important point is that the Model doesn’t care how these Views are organized, it simply announces updates to its data as necessary through the framework’s event system.</p></li>
<li><p>It is not uncommon for modern MVC/MV* frameworks to provide a means of grouping Models together. In Backbone, these groups are called <q>Collections.</q> Managing Models in groups allows us to write application logic based on notifications from the group when a Model within the group changes. This avoids the need to manually observe individual Model instances. We’ll see this in action later in the book.</p></li>
<li><p>If you read older texts on MVC, you may come across a description of Models as also managing application <q>state.</q> In JavaScript applications state has a specific meaning, typically referring to the current state of a view or sub-view on a user’s screen at a fixed time. State is an important topic to consider when writing single-page applications. In JavaScript apps we care about state memory - that is, recalling a previous state or sharing it with someone else.</p></li>
</ul>
<h4 id="views"><a href="#TOC">Views</a></h4>
<ul>
<li><p>Users interact with Views, which usually means reading and editing Model data. For example, in our Todo application, Todo Model viewing happens in the user interface in the list of all Todo items. Within it, each Todo is rendered with its title and completed checkbox. Model editing is done through an <q>edit</q> View where a user who has selected a specific Todo edits its title in a form.</p></li>
<li><p>We define a <code>render()</code> utility within our View which is responsible for rendering the contents of the <code>Model</code> using a JavaScript templating engine (provided by Underscore.js) and updating the contents of our View, referenced by <code>el</code>.</p></li>
<li><p>We then add our <code>render()</code> callback as a Model subscriber, so the View can be triggered to update when the Model changes.</p></li>
<li><p>You may wonder where user interaction comes into play here. When users click on a Todo element within the View, it’s not the View’s responsibility to know what to do next. A Controller makes this decision. In Backbone, this is achieved by adding an event listener to the Todo’s element which delegates handling of the click to an event handler.</p></li>
</ul>
<p><strong>Templating</strong></p>
<p>In the context of JavaScript frameworks that support MVC/MV*, it is worth looking more closely at JavaScript templating and its relationship to Views.</p>
<p>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 <code>document.write</code> to inject the <q>template</q> 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.</p>
<p>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 <q>text/template</q>). Variables are delimited using a variable syntax (e.g <%= title %>).</p>
<p>JavaScript template libraries typically accept data in a number of formats, including JSON; a serialisation format that is always a string. The grunt work of populating templates with data is generally taken care of by the framework itself. This has several benefits, particularly when opting to store templates externally which enables applications to load templates dynamically on an as-needed basis.</p>
<p>Let’s compare two examples of HTML templates. One is implemented using the popular Handlebars.js library, and the other uses Underscore’s <q>microtemplates</q>.</p>
<p><strong>Handlebars.js:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw"><div</span><span class="ot"> class=</span><span class="st">"view"</span><span class="kw">></span>
<span class="kw"><input</span><span class="ot"> class=</span><span class="st">"toggle"</span><span class="ot"> type=</span><span class="st">"checkbox"</span> <span class="er">{{#if</span><span class="ot"> completed</span><span class="er">}}</span> <span class="er">"checked"</span> <span class="er">{{/if}}</span><span class="kw">></span>
<span class="kw"><label></span>{{title}}<span class="kw"></label></span>
<span class="kw"><button</span><span class="ot"> class=</span><span class="st">"destroy"</span><span class="kw">></button></span>
<span class="kw"></div></span>
<span class="kw"><input</span><span class="ot"> class=</span><span class="st">"edit"</span><span class="ot"> value=</span><span class="st">"{{title}}"</span><span class="kw">></span></code></pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw"><div</span><span class="ot"> class=</span><span class="st">"view"</span><span class="kw">></span>
<span class="kw"><input</span><span class="ot"> class=</span><span class="st">"toggle"</span><span class="ot"> type=</span><span class="st">"checkbox"</span> <span class="er"><%</span><span class="ot">=</span> <span class="st">completed</span> <span class="st">?</span> <span class="er">'checked'</span><span class="ot"> :</span> <span class="er">''</span> <span class="er">%</span><span class="kw">></span>>
<span class="kw"><label></span><span class="er"><</span>%- title %><span class="kw"></label></span>
<span class="kw"><button</span><span class="ot"> class=</span><span class="st">"destroy"</span><span class="kw">></button></span>
<span class="kw"></div></span>
<span class="kw"><input</span><span class="ot"> class=</span><span class="st">"edit"</span><span class="ot"> value=</span><span class="st">"</span><span class="er"><</span><span class="st">%= title %>"</span><span class="kw">></span></code></pre>
<p>You may also use double curly brackets (i.e <code>{{}}</code>) (or any other tag you feel comfortable with) in Microtemplates. In the case of curly brackets, this can be done by setting the Underscore <code>templateSettings</code> attribute as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">_</span>.<span class="fu">templateSettings</span> = { <span class="dt">interpolate </span>: <span class="ot">/</span><span class="fl">\{\{(</span><span class="ot">.</span><span class="fl">+?)\}\}</span><span class="ot">/g</span> };</code></pre>
<p><strong>A note on Navigation and State</strong></p>
<p>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’t automatically update the URL, the role of navigation thus falls to a <q>router</q>, which assists in managing application state (e.g., allowing users to bookmark a particular view they have navigated to). As routers are 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.</p>
<h4 id="controllers"><a href="#TOC">Controllers</a></h4>
<p>In our Todo application, a Controller would be responsible for handling changes the user made in the edit View for a particular Todo, updating a specific Todo Model when a user has finished editing.</p>
<p>It’s with Controllers that most JavaScript MVC frameworks depart from the traditional 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 the approach didn’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 <q>proper</q> role of Controllers in other JavaScript frameworks.</p>
<p>So does Backbone.js have Controllers? Not really. Backbone’s Views typically contain <q>Controller</q> logic, and Routers are used to help manage application state, but neither are true Controllers according to classical MVC.</p>
<p>In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone isn’t truly an MVC framework. It’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.</p>
<h2 id="what-does-mvc-give-us"><a href="#TOC">What does MVC give us?</a></h2>
<p>To summarize, the separation of concerns in MVC facilitates modularization of an application’s functionality and enables:</p>
<ul>
<li>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.</li>
<li>Decoupling Models and Views means that it’s straight-forward to write unit tests for business logic</li>
<li>Duplication of low-level Model and Controller code is eliminated across the application</li>
<li>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</li>
</ul>
<h3 id="delving-deeper-into-mvc"><a href="#TOC">Delving Deeper into MVC</a></h3>
<p>Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we’ll explore it a little further.</p>
<p>The GoF (Gang of Four) do not refer to MVC as a design pattern, but rather consider it a <q>set of classes to build a user interface.</q> In their view, it’s actually a variation of three other classical design patterns: the Observer (Pubish/Subscribe), Strategy, and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. I’ve covered some of these patterns in my other free book, <q>JavaScript Design Patterns For Beginners</q> if you would like to read about them further.</p>
<p>As we’ve discussed, Models represent application data, while Views handle what the user is presented on screen. As such, MVC relies on Publish/Subscribe for some of its core communication (something that surprisingly isn’t covered in many articles about the MVC pattern). When a Model is changed it <q>publishes</q> to the rest of the application that it has been updated. The <q>subscriber,</q> generally a Controller, then updates the View accordingly. The observer-viewer nature of this relationship is what facilitates multiple Views being attached to the same Model.</p>
<p>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’ responses to different user input and are an example of the Strategy pattern.</p>
<h3 id="summary"><a href="#TOC">Summary</a></h3>
<p>Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.</p>
<p>When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it’s opted to approach Models, Views, Controllers or other alternatives, as this can better help you understand how the framework is intended to be used.</p>
<h3 id="further-reading"><a href="#TOC">Further reading</a></h3>
<p>If you are interested in learning more about the variation of MVC which Backbone.js is better categorized under, please see the MVP (Model-View-Presenter) section in the appendix.</p>
<h2 id="fast-facts"><a href="#TOC">Fast facts</a></h2>
<h3 id="backbone.js"><a href="#TOC">Backbone.js</a></h3>
<ul>
<li>Core components: Model, View, Collection, Router. Enforces its own flavor of MV*</li>
<li>Used by large companies such as SoundCloud and Foursquare to build non-trivial applications</li>
<li>Event-driven communication between Views and Models. As we’ll see, it’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</li>
<li>Supports data bindings through manual events or a separate Key-value observing (KVO) library</li>
<li>Support for RESTful interfaces out of the box, so Models can be easily tied to a backend</li>
<li>Extensive eventing system. It’s <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/">trivial</a> to add support for pub/sub in Backbone</li>
<li>Prototypes are instantiated with the <code>new</code> keyword, which some developers prefer</li>
<li>Agnostic about templating frameworks, however Underscore’s micro-templating is available by default. Backbone works well with libraries like Handlebars</li>
<li>Doesn’t support deeply nested Models, though there are Backbone plugins such as <a href="https://github.com/PaulUithol/Backbone-relational">Backbone-relational</a> which can help</li>
<li>Clear and flexible conventions for structuring applications. Backbone doesn’t force usage of all of its components and can work with only those needed.</li>
</ul>
<h1 id="backbone-basics"><a href="#TOC">Backbone Basics</a></h1>
<p>In this section, you’ll learn the essentials of Backbone’s models, views, collections, events, and routers. This isn’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.</p>
<h2 id="models-1"><a href="#TOC">Models</a></h2>
<p>Backbone models contain 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 todo item including its attributes like title (todo content) and completed (current state of the todo).</p>
<p>Models can be created by extending <code>Backbone.Model</code> as follows:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({});
<span class="co">// We can then create our own concrete instance of a (Todo) model</span>
<span class="co">// with no values at all:</span>
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="co">// Following logs: {}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(todo1));
<span class="co">// or with some arbitrary data:</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">'Check the attributes of both model instances in the console.'</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// Following logs: {"title":"Check the attributes of both model instances in the console.","completed":true}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(todo2));</code></pre>
<h4 id="initialization"><a href="#TOC">Initialization</a></h4>
<p>The <code>initialize()</code> method is called when a new instance of a model is created. Its use is optional; however you’ll see why it’s good practice to use it below.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'This model has been initialized.'</span>);
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="co">// Logs: This model has been initialized.</span></code></pre>
<p><strong>Default values</strong></p>
<p>There are times when you want your model to have a set of default values (e.g., in a scenario where a complete set of data isn’t provided by the user). This can be set using a property called <code>defaults</code> in your model.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Now we can create our concrete instance of the model</span>
<span class="co">// with default values as follows:</span>
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="co">// Following logs: {"title":"","completed":false}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(todo1));
<span class="co">// Or we could instantiate it with some of the attributes (e.g., with custom title):</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">'Check attributes of the logged models in the console.'</span>
});
<span class="co">// Following logs: {"title":"Check attributes of the logged models in the console.","completed":false}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(todo2));
<span class="co">// Or override all of the default attributes:</span>
<span class="kw">var</span> todo3 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="ch">'This todo is done, so take no action on this one.'</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// Following logs: {"title":"This todo is done, so take no action on this one.","completed":true} </span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">JSON</span>.<span class="fu">stringify</span>(todo3));</code></pre>
<h4 id="getters-setters"><a href="#TOC">Getters & Setters</a></h4>
<p><strong>Model.get()</strong></p>
<p><code>Model.get()</code> provides easy access to a model’s attributes.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo1</span>.<span class="fu">get</span>(<span class="ch">'title'</span>)); <span class="co">// empty string</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo1</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// false</span>
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="st">"Retrieved with model's get() method."</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">get</span>(<span class="ch">'title'</span>)); <span class="co">// Retrieved with model's get() method.</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// true</span></code></pre>
<p>If you need to read or clone all of a model’s data attributes, use its <code>toJSON()</code> method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When <code>JSON.stringify()</code> is passed an object with a <code>toJSON()</code> method, it stringifies the return value of <code>toJSON()</code> instead of the original object. The examples in the previous section took advantage of this feature when they called <code>JSON.stringify()</code> to log model instances.)</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="kw">var</span> todo1 = <span class="kw">new</span> Todo();
<span class="kw">var</span> todo1Attributes = <span class="kw">todo1</span>.<span class="fu">toJSON</span>();
<span class="co">// Following logs: {"title":"","completed":false} </span>
<span class="kw">console</span>.<span class="fu">log</span>(todo1Attributes);
<span class="kw">var</span> todo2 = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="st">"Try these examples and check results in console."</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="co">// logs: {"title":"Try these examples and check results in console.","completed":true}</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todo2</span>.<span class="fu">toJSON</span>());</code></pre>
<p><strong>Model.set()</strong></p>
<p><code>Model.set()</code> allows us to pass attributes into an instance of our model. Backbone uses Model.set() to know when to broadcast to its listeners that the model’s data has changed.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
}
});
<span class="co">// Setting the value of attributes via instantiation</span>
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo({
<span class="dt">title</span>: <span class="st">"Set through instantiation."</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Todo title: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'title'</span>)); <span class="co">// Todo title: Set through instantiation.</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Completed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// Completed: false</span>
<span class="co">// Set single attribute value at a time through Model.set():</span>
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="st">"title"</span>, <span class="st">"Title attribute set through Model.set()."</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Todo title: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'title'</span>)); <span class="co">// Todo title: Title attribute set through Model.set().</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Completed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// Completed: false</span>
<span class="co">// Set map of attributes through Model.set():</span>
<span class="kw">myTodo</span>.<span class="fu">set</span>({
<span class="dt">title</span>: <span class="st">"Both attributes set through Model.set()."</span>,
<span class="dt">completed</span>: <span class="kw">true</span>
});
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Todo title: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'title'</span>)); <span class="co">// Todo title: Both attributes set through Model.set().</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Completed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// Completed: true</span></code></pre>
<p><strong>Direct access</strong></p>
<p>Models store attributes internally in the <code>Model.attributes</code> object which can be accessed directly if necessary. But remember it is best practice to use Model.get(), Model.set(), or direct instantiation as explained above.</p>
<h4 id="listening-for-changes-to-your-model"><a href="#TOC">Listening for changes to your model</a></h4>
<p>If you want to receive a notification when a Backbone model changes you can bind a listener to the model for its change event. A convenient place to add listeners is in the <code>initialize()</code> function as shown below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'This model has been initialized.'</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="ch">'change'</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'- Values for this model have changed.'</span>);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">'title'</span>, <span class="ch">'The listener is triggered whenever an attribute value changes.'</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Title has changed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'title'</span>));
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">'completed'</span>, <span class="kw">true</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Completed has changed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>));
<span class="kw">myTodo</span>.<span class="fu">set</span>({
<span class="dt">title</span>: <span class="ch">'Changing more than one attribute at the same time only triggers the listener once.'</span>,
<span class="ch">'complete'</span>: <span class="kw">true</span>
});
<span class="co">// Above logs:</span>
<span class="co">// This model has been initialized.</span>
<span class="co">// - Values for this model have changed.</span>
<span class="co">// Title has changed: The listener is triggered whenever an attribute value changes.</span>
<span class="co">// - Values for this model have changed.</span>
<span class="co">// Completed has changed: true</span>
<span class="co">// - Values for this model have changed.</span></code></pre>
<p>You can also listen for changes to individual attributes in a Backbone model. In the following example, we log a message whenever a specific attribute (the title of our Todo model) is altered.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="co">// Default todo attribute values</span>
<span class="dt">defaults</span>: {
<span class="dt">title</span>: <span class="ch">''</span>,
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'This model has been initialized.'</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="ch">'change:title'</span>, <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Title value for this model has changed.'</span>);
});
},
<span class="dt">setTitle</span>: <span class="kw">function</span>(newTitle){
<span class="kw">this</span>.<span class="fu">set</span>({ <span class="dt">title</span>: newTitle });
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="co">// Both of the following changes trigger the listener:</span>
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">'title'</span>, <span class="ch">'Check what\'s logged.'</span>);
<span class="kw">myTodo</span>.<span class="fu">setTitle</span>(<span class="ch">'Go fishing on Sunday.'</span>);
<span class="co">// But, this change type is not observed, so no listener is triggered:</span>
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">'completed'</span>, <span class="kw">true</span>);
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'Todo set as completed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>));
<span class="co">// Above logs:</span>
<span class="co">// This model has been initialized.</span>
<span class="co">// Title value for this model has changed.</span>
<span class="co">// Title value for this model has changed.</span>
<span class="co">// Todo set as completed: true</span></code></pre>
<h4 id="validation"><a href="#TOC">Validation</a></h4>
<p>Backbone supports model validation through <code>Model.validate()</code>, which allows checking the attribute values for a model prior to setting them.</p>
<p>Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from <code>.validate()</code>. If they are invalid, an error value should be returned instead. If an error is returned, an <code>invalid</code> event will occur and listeners will be passed the unmodified model and the error value.</p>
<p>Validation automatically occurs when the model is persisted using the <code>.save()</code> method or when <code>.set()</code> is called with the validate option set to true. A basic validation example can be seen below:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Todo = <span class="kw">Backbone.Model</span>.<span class="fu">extend</span>({
<span class="dt">defaults</span>: {
<span class="dt">completed</span>: <span class="kw">false</span>
},
<span class="dt">validate</span>: <span class="kw">function</span>(attribs){
<span class="kw">if</span>(<span class="kw">attribs</span>.<span class="fu">title</span> === undefined){
<span class="kw">return</span> <span class="st">"Remember to set a title for your todo."</span>;
}
},
<span class="dt">initialize</span>: <span class="kw">function</span>(){
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'This model has been initialized.'</span>);
<span class="kw">this</span>.<span class="fu">on</span>(<span class="st">"invalid"</span>, <span class="kw">function</span>(model, error){
<span class="kw">console</span>.<span class="fu">log</span>(error);
});
}
});
<span class="kw">var</span> myTodo = <span class="kw">new</span> Todo();
<span class="kw">myTodo</span>.<span class="fu">set</span>(<span class="ch">'completed'</span>, <span class="kw">true</span>, {<span class="dt">validate</span>: <span class="kw">true</span>}); <span class="co">// logs: Remember to set a title for your todo.</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="ch">'completed: '</span> + <span class="kw">myTodo</span>.<span class="fu">get</span>(<span class="ch">'completed'</span>)); <span class="co">// completed: false</span></code></pre>
<p><strong>Note</strong>: the <code>attributes</code> object passed to the <code>validate</code> function represents what the attributes would be after completing the current <code>set()</code> or <code>save()</code>. This object is distinct from the current attributes of the model and from the parameters passed to the operation. Since it is created by shallow copy, it is not possible to change any Number, String, or Boolean attribute of the input within the function, but it <em>is</em> possible to change attributes in nested objects.</p>
<p>An example of this (by @fivetanley) is available <a href="http://jsfiddle.net/2NdDY/7/">here</a>.</p>
<h2 id="views-1"><a href="#TOC">Views</a></h2>
<p>Views in Backbone don’t contain the HTML markup for your application; they contain the logic behind the presentation of the model’s data to the user. This is usually achieved using JavaScript templating (e.g., Underscore Microtemplates, Mustache, jQuery-tmpl, etc.). A view’s <code>render()</code> method can be bound to a model’s <code>change()</code> event, enabling the view to instantly reflect model changes without requiring a full page refresh.</p>
<h4 id="creating-new-views"><a href="#TOC">Creating new views</a></h4>
<p>Creating a new view is relatively straight-forward and similar to creating new models. To create a new View, simply extend <code>Backbone.View</code>. We introduced the sample TodoView below in the previous chapter; now let’s take a closer look at how it works.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodoView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="ch">'li'</span>,
<span class="co">// Cache the template function for a single item.</span>
<span class="dt">todoTpl</span>: <span class="kw">_</span>.<span class="fu">template</span>( <span class="st">"An example template"</span> ),
<span class="dt">events</span>: {
<span class="ch">'dblclick label'</span>: <span class="ch">'edit'</span>,
<span class="ch">'keypress .edit'</span>: <span class="ch">'updateOnEnter'</span>,
<span class="ch">'blur .edit'</span>: <span class="ch">'close'</span>
},
<span class="co">// Re-render the titles of the todo item.</span>
<span class="dt">render</span>: <span class="kw">function</span>() {
<span class="kw">this</span>.$<span class="fu">el</span>.<span class="fu">html</span>( <span class="kw">this</span>.<span class="fu">todoTpl</span>( <span class="kw">this</span>.<span class="fu">model</span>.<span class="fu">toJSON</span>() ) );
<span class="kw">this</span>.<span class="fu">input</span> = <span class="kw">this</span>.$(<span class="ch">'.edit'</span>);
<span class="kw">return</span> <span class="kw">this</span>;
},
<span class="dt">edit</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo label is double clicked</span>
},
<span class="dt">close</span>: <span class="kw">function</span>() {
<span class="co">// executed when todo loses focus</span>
},
<span class="dt">updateOnEnter</span>: <span class="kw">function</span>( e ) {
<span class="co">// executed on each keypress when in todo edit mode,</span>
<span class="co">// but we'll wait for enter to get in action</span>
}
});
<span class="kw">var</span> todoView = <span class="kw">new</span> TodoView();
<span class="co">// log reference to a DOM element that corresponds to the view instance</span>
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todoView</span>.<span class="fu">el</span>); <span class="co">// logs <li></li></span></code></pre>
<h4 id="what-is-el"><a href="#TOC">What is <code>el</code>?</a></h4>
<p>The central property of a view is <code>el</code> (the value logged in the last statement of the example). What is <code>el</code> and how is it defined?</p>
<p><code>el</code> is basically a reference to a DOM element and all views must have one. Views can use <code>el</code> to compose their element’s content and then insert it into the DOM all at once, which makes for faster rendering because the browser performs the minimum required number of reflows and repaints.</p>
<p>There are two ways to associate a DOM element with a view: a new element can be created for the view and subsequently added to the DOM or a reference can be made to an element which already exists in the page.</p>
<p>If you want to create a new element for your view, set any combination of the following properties on the view: <code>tagName</code>, <code>id</code> and <code>className</code>. A new element will be created for you by the framework and a reference to it will be available at the <code>el</code> property. If nothing is specified <code>tagName</code> defaults to <code>div</code>.</p>
<p>In the example above, <code>tagName</code> is set to <q>li</q>, resulting in creation of an li element. The following example creates a ul element with id and class attributes:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> TodosView = <span class="kw">Backbone.View</span>.<span class="fu">extend</span>({
<span class="dt">tagName</span>: <span class="ch">'ul'</span>, <span class="co">// required, but defaults to 'div' if not set</span>
<span class="dt">className</span>: <span class="ch">'container'</span>, <span class="co">// optional, you can assign multiple classes to this property like so: 'container homepage'</span>
<span class="dt">id</span>: <span class="ch">'todos'</span>, <span class="co">// optional</span>
});
<span class="kw">var</span> todosView = <span class="kw">new</span> TodosView();
<span class="kw">console</span>.<span class="fu">log</span>(<span class="kw">todosView</span>.<span class="fu">el</span>); <span class="co">// logs <ul id="todos" class="container"></ul></span></code></pre>
<p>The above code creates the DOM element below but doesn’t append it to the DOM.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw"><ul</span><span class="ot"> id=</span><span class="st">"todos"</span><span class="ot"> class=</span><span class="st">"container"</span><span class="kw">></ul></span></code></pre>
<p>If the element already exists in the page, you can set <code>el</code> as a CSS selector that matches the element.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">el</span>: <span class="ch">'#footer'</span></code></pre>
<p>Alternatively, you can set <code>el</code> to an existing element when creating the view:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> todosView = <span class="kw">new</span> TodosView({<span class="dt">el</span>: $(<span class="ch">'#footer'</span>)});</code></pre>
<p><strong>$el and $()</strong></p>
<p>View logic often needs to invoke jQuery or Zepto functions on the <code>el</code> element and elements nested within it. Backbone makes it easy to do so by defining the <code>$el</code> property and <code>$()</code> function. The <code>view.$el</code> property is equivalent to <code>$(view.el)</code> and <code>view.$(selector)</code> is equivalent to <code>$(view.el).find(selector)</code>. In our TodosView example’s render method, we see <code>this.$el</code> used to set the HTML of the element and <code>this.$()</code> used to find subelements of class <q>edit</q>.</p>
<p><strong>Understanding <code>render()</code></strong></p>
<p><code>render()</code> is an optional function that defines the logic for rendering a template. We’ll use Underscore’s micro-templating in these examples, but remember you can use other templating frameworks if you prefer. Our example will reference the following HTML markup:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="er"><</span>!doctype html>
<span class="kw"><html</span><span class="ot"> lang=</span><span class="st">"en"</span><span class="kw">></span>
<span class="kw"><head></span>
<span class="kw"><meta</span><span class="ot"> charset=</span><span class="st">"utf-8"</span><span class="kw">></span>
<span class="kw"><title></title></span>
<span class="kw"><meta</span><span class="ot"> name=</span><span class="st">"description"</span><span class="ot"> content=</span><span class="st">""</span><span class="kw">></span>
<span class="kw"></head></span>
<span class="kw"><body></span>
<span class="kw"><div</span><span class="ot"> id=</span><span class="st">"todo"</span><span class="kw">></span>
<span class="kw"></div></span>
<span class="kw"><script</span><span class="ot"> type=</span><span class="st">"text/template"</span><span class="ot"> id=</span><span class="st">"item-template"</span><span class="kw">></span>