724 learning javascript design patterns

199 124 0
  • Loading ...
    Loading ...
    Loading ...

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Tài liệu liên quan

Thông tin tài liệu

Ngày đăng: 06/03/2019, 17:14

www.it-ebooks.info Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo www.it-ebooks.info Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani All rights reserved Revision History for the : 2012-05-01 Early release revision See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details ISBN: 978-1-449-33181-8 1335906805 www.it-ebooks.info Table of Contents Preface ix Introduction What is a Pattern? We already use patterns everyday 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three The Structure Of A Design Pattern Writing Design Patterns 11 Anti-Patterns 13 Categories Of Design Pattern 15 Creational Design Patterns Structural Design Patterns Behavioral Design Patterns 15 16 16 Design Pattern Categorization 17 A brief note on classes 17 JavaScript Design Patterns 21 The Creational Pattern The Constructor Pattern Basic Constructors Constructors With Prototypes The Singleton Pattern The Module Pattern 22 23 23 24 24 27 iii www.it-ebooks.info Modules Object Literals The Module Pattern The Revealing Module Pattern The Observer Pattern Advantages Disadvantages Implementations The Mediator Pattern Advantages & Disadvantages Mediator Vs Observer Mediator Vs Facade The Prototype Pattern The Command Pattern The Facade Pattern The Factory Pattern When To Use The Factory Pattern When Not To Use The Factory Pattern The Mixin Pattern The Decorator Pattern Subclassing Decorators Example 1: Basic decoration of existing object constructors with new functionality Example 2: Simply decorate objects with multiple decorators Pseudo-classical decorators Interfaces This variation of decorators and abstract decorators Implementing decorators with jQuery Pros and cons of the pattern 27 27 29 36 37 38 39 39 49 50 51 51 52 54 56 58 59 59 60 61 61 63 63 64 65 65 66 69 70 10 Flyweight 71 Flyweight and the data layer Converting code to use the Flyweight pattern A Basic Factory Managing the extrinsic states The Flyweight pattern and the DOM Example 1: Centralized event handling Example 2: Using the Flyweight for Performance Gains 72 72 74 74 76 76 77 11 MV* Patterns 79 MVC Smalltalk-80 MVC 79 79 iv | Table of Contents www.it-ebooks.info MVC For JavaScript Developers Models Views Controllers Controllers in another library (Spine.js) vs Backbone.js What does MVC give us? Delving deeper Summary MVP Models, Views & Presenters MVP or MVC? MVC, MVP and Backbone.js MVVM History Model View ViewModel Recap: The View and the ViewModel Recap: The ViewModel and the Model Pros and Cons Advantages Disadvantages MVVM With Looser Data-Bindings MVC Vs MVP Vs MVVM Backbone.js Vs KnockoutJS Namespacing Patterns What is namespacing? Advanced namespacing patterns Automating nested namespacing Dependency declaration pattern Deep object extension Namespacing Fundamentals 1.Single global variables Prefix namespacing Object literal notation Nested namespacing Immediately-invoked Function Expressions (IIFE)s Namespace injection 80 81 82 85 86 87 88 88 88 89 90 90 92 92 93 94 96 98 98 98 98 98 99 103 103 104 104 105 105 107 108 110 111 111 112 114 115 117 12 Design Patterns in jQuery Core 121 Module Pattern Lazy Initialization The Composite Pattern 121 122 123 Table of Contents | v www.it-ebooks.info The Adapter Pattern The Facade Pattern The Observer Pattern The Iterator Pattern The Strategy Pattern The Proxy Pattern The Builder Pattern The Prototype Pattern 123 124 125 126 127 127 128 128 13 Modern Modular JavaScript Design Patterns 131 The Importance Of Decoupling Your Application A Note On Script Loaders AMD A Format For Writing Modular JavaScript In The Browser Getting Started With Modules AMD Modules With Dojo AMD Module Design Patterns (Dojo) AMD Modules With jQuery AMD Conclusions CommonJS A Module Format Optimized For The Server Getting Started AMD && CommonJS Competing, But Equally Valid Standards Basic AMD Hybrid Format (John Hann) AMD/CommonJS Universal Module Definition (Variation 2, UMDjs) Extensible UMD Plugins With (Variation by myself and Thomas Davis) ES Harmony Modules Of The Future Modules With Imports And Exports Modules Loaded From Remote Sources Module Loader API CommonJS-like Modules For The Server Classes With Constructors, Getters & Setters Conclusions And Further Reading A Review 131 132 132 132 133 137 138 139 141 141 141 141 144 145 145 146 148 148 148 149 150 150 150 152 14 Bonus: jQuery Plugin Design Patterns 153 Patterns Note A Lightweight Start Further Reading “Complete” Widget Factory Further Reading Namespacing And Nested Namespacing vi | Table of Contents www.it-ebooks.info 154 154 155 156 157 159 159 Further Reading Custom Events For Pub/Sub (With The Widget factory) Further Reading Prototypal Inheritance With The DOM-To-Object Bridge Pattern Further Reading jQuery UI Widget Factory Bridge Further Reading jQuery Mobile Widgets With The Widget factory RequireJS And The jQuery UI Widget Factory Further Reading Globally And Per-Call Overridable Options (Best Options Pattern) Further Reading A Highly Configurable And Mutable Plugin Further Reading UMD: AMD And CommonJS-Compatible Modules For Plugins Further Reading What Makes A Good Plugin Beyond Patterns? 161 161 162 162 164 164 166 167 169 172 172 174 174 176 176 179 179 15 Conclusions 183 16 References 185 Table of Contents | vii www.it-ebooks.info www.it-ebooks.info 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 language 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 www.it-ebooks.info })( jQuery, window, document ); Usage: $('#elem').pluginName({ key: "foobar" }); Further Reading • jQuery Pluginization and the accompanying gist, Ben Alman A Highly Configurable And Mutable Plugin Like Alex Sexton’s pattern, the following logic for our plugin isn’t nested in a jQuery plugin itself We instead define our plugin’s logic using a constructor and an object literal defined on its prototype, using jQuery for the actual instantiation of the plugin object Customization is taken to the next level by employing two little tricks, one of which you’ve seen in previous patterns: • Options can be overridden both globally and per collection of elements; • Options can be customized on a per-element level through HTML5 data attributes (as shown below) This facilitates plugin behavior that can be applied to a collection of elements but then customized inline without the need to instantiate each element with a different default value You don’t see the latter option in the wild too often, but it can be a significantly cleaner solution (as long as you don’t mind the inline approach) If you’re wondering where this could be useful, imagine writing a draggable plugin for a large set of elements You could go about customizing their options like this: javascript $('.item-a').draggable({'defaultPosition':'top-left'}); $('.item-b').draggable({'defaultPosition':'bottom-right'}); $('.item-c').draggable({'defaultPosition':'bottom-left'}); //etc But using our patterns inline approach, the following would be possible: javascript $('.items').draggable(); html And so on You may well have a preference for one of these approaches, but it is another potentially useful pattern to be aware of 174 | Chapter 14: Bonus: jQuery Plugin Design Patterns www.it-ebooks.info /* * 'Highly configurable' mutable plugin boilerplate * Author: @markdalgleish * Further changes, comments: @addyosmani * Licensed under the MIT license */ // Note that with this pattern, as per Alex Sexton's, the plugin logic // hasn't been nested in a jQuery plugin Instead, we just use // jQuery for its instantiation ;(function( $, window, document, undefined ){ // our plugin constructor var Plugin = function( elem, options ){ this.elem = elem; this.$elem = $(elem); this.options = options; // This next line takes advantage of HTML5 data attributes // to support customization of the plugin on a per-element // basis For example, //
- Xem thêm -

Xem thêm: 724 learning javascript design patterns , 724 learning javascript design patterns , Chapter 2. What is a Pattern?, Chapter 4. The Structure Of A Design Pattern, Chapter 7. Categories Of Design Pattern, MVC, MVP and Backbone.js, Chapter 12. Design Patterns in jQuery Core, Chapter 13. Modern Modular JavaScript Design Patterns, Chapter 14. Bonus: jQuery Plugin Design Patterns

Mục lục

Xem thêm