Learning Javascript Design Patterns
Total Page:16
File Type:pdf, Size:1020Kb
Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern 29 The Revealing Module Pattern 36 The Observer Pattern 37 Advantages 38 Disadvantages 39 Implementations 39 The Mediator Pattern 49 Advantages & Disadvantages 50 Mediator Vs. Observer 51 Mediator Vs. Facade 51 The Prototype Pattern 52 The Command Pattern 54 The Facade Pattern 56 The Factory Pattern 58 When To Use The Factory Pattern 59 When Not To Use The Factory Pattern 59 The Mixin Pattern 60 The Decorator Pattern 61 Subclassing 61 Decorators 63 Example 1: Basic decoration of existing object constructors with new functionality 63 Example 2: Simply decorate objects with multiple decorators 64 Pseudo-classical decorators 65 Interfaces 65 This variation of decorators and abstract decorators 66 Implementing decorators with jQuery 69 Pros and cons of the pattern 70 10. Flyweight . ........................................................... 71 Flyweight and the data layer 72 Converting code to use the Flyweight pattern 72 A Basic Factory 74 Managing the extrinsic states 74 The Flyweight pattern and the DOM 76 Example 1: Centralized event handling 76 Example 2: Using the Flyweight for Performance Gains 77 11. MV* Patterns . ......................................................... 79 MVC 79 Smalltalk-80 MVC 79 iv | Table of Contents MVC For JavaScript Developers 80 Models 81 Views 82 Controllers 85 Controllers in another library (Spine.js) vs Backbone.js 86 What does MVC give us? 87 Delving deeper 88 Summary 88 MVP 88 Models, Views & Presenters 89 MVP or MVC? 90 MVC, MVP and Backbone.js 90 MVVM 92 History 92 Model 93 View 94 ViewModel 96 Recap: The View and the ViewModel 98 Recap: The ViewModel and the Model 98 Pros and Cons 98 Advantages 98 Disadvantages 98 MVVM With Looser Data-Bindings 99 MVC Vs. MVP Vs. MVVM 103 Backbone.js Vs. KnockoutJS 103 Namespacing Patterns 104 What is namespacing? 104 Advanced namespacing patterns 105 Automating nested namespacing 105 Dependency declaration pattern 107 Deep object extension 108 Namespacing Fundamentals 110 1.Single global variables 111 2. Prefix namespacing 111 3. Object literal notation 112 4. Nested namespacing 114 5. Immediately-invoked Function Expressions (IIFE)s 115 6. Namespace injection 117 12. Design Patterns in jQuery Core .......................................... 121 Module Pattern 121 Lazy Initialization 122 The Composite Pattern 123 Table of Contents | v The Adapter Pattern 123 The Facade Pattern 124 The Observer Pattern 125 The Iterator Pattern 126 The Strategy Pattern 127 The Proxy Pattern 127 The Builder Pattern 128 The Prototype Pattern 128 13. Modern Modular JavaScript Design Patterns ............................... 131 The Importance Of Decoupling Your Application 131 A Note On Script Loaders 132 AMD 132 A Format For Writing Modular JavaScript In The Browser 132 Getting Started With Modules 133 AMD Modules With Dojo 137 AMD Module Design Patterns (Dojo) 138 AMD Modules With jQuery 139 AMD Conclusions 141 CommonJS 141 A Module Format Optimized For The Server 141 Getting Started 141 AMD && CommonJS Competing, But Equally Valid Standards 144 Basic AMD Hybrid Format (John Hann) 145 AMD/CommonJS Universal Module Definition (Variation 2, UMDjs) 145 Extensible UMD Plugins With (Variation by myself and Thomas Davis). 146 ES Harmony 148 Modules Of The Future 148 Modules With Imports And Exports 148 Modules Loaded From Remote Sources 149 Module Loader API 150 CommonJS-like Modules For The Server 150 Classes With Constructors, Getters & Setters 150 Conclusions And Further Reading A Review 152 14. Bonus: jQuery Plugin Design Patterns .................................... 153 Patterns 154 Note 154 A Lightweight Start 155 Further Reading 156 “Complete” Widget Factory 157 Further Reading 159 Namespacing And Nested Namespacing 159 vi | Table of Contents Further Reading 161 Custom Events For Pub/Sub (With The Widget factory) 161 Further Reading 162 Prototypal Inheritance With The DOM-To-Object Bridge Pattern 162 Further Reading 164 jQuery UI Widget Factory Bridge 164 Further Reading 166 jQuery Mobile Widgets With The Widget factory 167 RequireJS And The jQuery UI Widget Factory 169 Further Reading 172 Globally And Per-Call Overridable Options (Best Options Pattern) 172 Further Reading 174 A Highly Configurable And Mutable Plugin 174 Further Reading 176 UMD: AMD And CommonJS-Compatible Modules For Plugins 176 Further Reading 179 What Makes A Good Plugin Beyond Patterns? 179 15. Conclusions .......................................................... 183 16. References ........................................................... 185 Table of Contents | vii Preface Design patterns are reusable solutions to commonly occurring problems in software design. They are both exciting and a fascinating topic to explore in any programming language. One reason for this is that they help us build upon the combined experience of many developers that came before us and ensure we structure our code in an optimized way, meeting the needs of problems we're attempting to solve. Design patterns also provide us a common vocabulary to describe solutions. This can be significantly simpler than describing syntax and semantics when we're attempting to convey a way of structuring a solution in code form to others. In this book we will explore applying both classical and modern design patterns to the JavaScript programming language. Target Audience This book is targeted at professional developers wishing to improve their knowledge of design patterns and how they can be applied to the JavaScript programming lan- guage. Some of the concepts covered (closures, prototypal inheritance) will assume a level of basic prior knowledge and understanding. If you find yourself needing to read further about these topics, a list of suggested titles is provided for convenience. If you would like to learn how to write beautiful, structured and organized code, I believe this is the book for you. Acknowledgments I will always be grateful for the talented technical reviewers who helped review and improve this book, including those from the community at large. The knowledge and enthusiasm they brought to the project was simply amazing. The official technical re- ix viewers tweets and blogs are also a regular source of both ideas and inspiration and I wholeheartedly recommend checking them out. • Luke Smith (http://lucassmith.name, @ls_n) • Nicholas Zakas (http://nczonline.net, @slicknet) • Andrée Hansson (http://andreehansson.se, @peolanha) • Alex Sexton (http://alexsexton.com, @slexaxton) I would also like to thank Rebecca Murphey (http://rebeccamurphey.com, @rmur- phey) for providing the inspiration to write this book and more importantly, continue to make it both available on GitHub and via O'Reilly. Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was putting together this publication. Credits Whilst some of the patterns covered in this book were implemented based on personal experience, many of them have been previously identified by the JavaScript community. This work is as such the production of the combined experience of a number of devel- opers. Similar to Stoyan Stefanov's logical approach to preventing interruption of the narrative with credits (in JavaScript Patterns), I have listed credits and suggested reading for any content covered in the references section. If any articles or links have been missed in the list of references, please accept my heartfelt apologies. If you contact me I'll be sure to update them to include you on the list. Reading Whilst this book is targeted at both beginners and intermediate developers, a basic understanding of JavaScript fundamentals is assumed. Should you wish to learn more about the language, I am happy to recommend the following titles: • JavaScript: The Definitive Guide by David Flanagan • Eloquent JavaScript by Marijn Haverbeke • JavaScript Patterns by Stoyan Stefanov • Writing Maintainable JavaScript by Nicholas Zakas • JavaScript: The Good Parts by Douglas Crockford x | Preface CHAPTER 1 Introduction