Buy ebook Learning JavaScript Design Patterns Addy Osmani cheap price
Buy ebook Learning JavaScript Design Patterns Addy Osmani cheap price
com
https://ebookname.com/product/learning-javascript-design-
patterns-addy-osmani/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookname.com/product/learning-javascript-design-patterns-a-
javascript-and-react-developer-s-guide-2nd-edition-adnan-osmani/
ebookname.com
https://ebookname.com/product/pro-javascript-design-patterns-1st-
edition-ross-harmes/
ebookname.com
https://ebookname.com/product/learning-python-design-patterns-2nd-
edition-chetan-giridhar/
ebookname.com
https://ebookname.com/product/the-body-politic-in-roman-political-
thought-1st-edition-julia-mebane/
ebookname.com
Cambridge English for Nursing Pre intermediate Student s
Book with Audio CD Cambridge English For Series 1st
Edition Allum
https://ebookname.com/product/cambridge-english-for-nursing-pre-
intermediate-student-s-book-with-audio-cd-cambridge-english-for-
series-1st-edition-allum/
ebookname.com
https://ebookname.com/product/smart-buildings-systems-for-architects-
owners-and-builders-james-m-sinopoli/
ebookname.com
https://ebookname.com/product/dietary-modulation-of-cell-signaling-
pathways-1st-edition-zigang-dong/
ebookname.com
https://ebookname.com/product/global-politics-9th-edition-james-ray/
ebookname.com
https://ebookname.com/product/materials-degradation-and-its-control-
by-surface-engineering-3rd-edition-andrew-w-batchelor/
ebookname.com
WHO Guidelines for the Management of Postpartum
Haemorrhage and Retained Placenta 1st Edition World Health
Organization
https://ebookname.com/product/who-guidelines-for-the-management-of-
postpartum-haemorrhage-and-retained-placenta-1st-edition-world-health-
organization/
ebookname.com
Learning JavaScript Design
Patterns
Addy Osmani
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
6. Anti-Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
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
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
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
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
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
One of the most important aspects of writing maintainable code is being able to notice
the recurring themes in that code and optimize them. This is an area where knowledge
of design patterns can prove invaluable.
In the first part of this book, we will explore the history and importance of design
patterns which can really be applied to any programming language. If you're already
sold on or are familiar with this history, feel free to skip to the chapter 'What is a
Pattern?' to continue reading.
Design patterns can be traced back to the early work of a civil engineer named Chris-
topher Alexander. He would often write publications about his experience in solving
design issues and how they related to buildings and towns. One day, it occurred to
Alexander that when used time and time again, certain design constructs lead to a
desired optimal effect.
In collaboration with Sara Ishikawa and Murray Silverstein, Alexander produced a
pattern language that would help empower anyone wishing to design and build at any
scale. This was published back in 1977 in a paper titled 'A Pattern Language', which
was later released as a complete hardcover book.
Some 30 years ago, software engineers began to incorporate the principles Alexander
had written about into the first documentation about design patterns, which was to be
a guide for novice developers looking to improve their coding skills. It's important to
note that the concepts behind design patterns have actually been around in the pro-
gramming industry since its inception, albeit in a less formalized form.
One of the first and arguably most iconic formal works published on design patterns
in software engineering was a book in 1995 called Design Patterns: Elements Of Reusable
Object-Oriented Software. This was written by Erich Gamma,Richard Helm,Ralph
Johnson andJohn Vlissides - a group that became known as the Gang of Four (or GoF
for short).
The GoF's publication is considered quite instrumental to pushing the concept of de-
sign patterns further in our field as it describes a number of development techniques
1
and pitfalls as well as providing twenty-three core Object-Oriented design patterns
frequently used around the world today. We will be covering these patterns in more
detail in the section ‘Categories of Design Patterns’.
In this book, we will take a look at a number of popular JavaScript design patterns and
explore why certain patterns may be more suitable for your projects than others. Re-
member that patterns can be applied not just to vanilla JavaScript (i.e standard Java-
Script code), but also to abstracted libraries such as jQuery or dojo as well. Before we
begin, let’s look at the exact definition of a ‘pattern’ in software design.
2 | Chapter 1: Introduction
CHAPTER 2
What is a Pattern?
3
gramming language) you are working with, design patterns can be applied to im-
prove the structure of your code.
• Certain patterns can actually decrease the overall file-size footprint of your
code by avoiding repetition.By encouraging developers to look more closely at
their solutions for areas where instant reductions in repetition can be made, e.g.
reducing the number of functions performing similar processes in favor of a single
generalized function, the overall size of your codebase can be decreased.
• Patterns add to a developers vocabulary, which makes communication
faster.
• Patterns that are frequently used can be improved over time by harnessing
the collective experiences other developers using those patterns contribute
back to the design pattern community. In some cases this leads to the creation
of entirely new design patterns whilst in others it can lead to the provision of im-
proved guidelines on how specific patterns can be best used. This can ensure that
pattern-based solutions continue to become more robust than ad-hoc solutions
may be.
Remember that not every algorithm, best-practice or solution represents what might
be considered a complete pattern. There may be a few key ingredients here that are
missing and the pattern community is generally weary of something claiming to be one
unless it has been heavily vetted. Even if something is presented to us which appears
to meet the criteria for a pattern, it should not be considered one until it has undergone
suitable periods of scrutiny and testing by others.
Looking back upon the work by Alexander once more, he claims that a pattern should
both be a process and a ‘thing’. This definition is obtuse on purpose as he follows by
saying that it is the process should create the ‘thing’. This is a reason why patterns
generally focus on addressing a visually identifiable structure i.e you should be able to
visually depict (or draw) a picture representing the structure that placing the pattern
into practice results in.
In studying design patterns, you may come across the term ‘proto-pattern’ quite fre-
quently. What is this? Well, a pattern that has not yet been known to pass the ‘pattern’-
ity tests is usually referred to as a proto-pattern. Proto-patterns may result from the
work of someone that has established a particular solution that is worthy of sharing
with the community, but may not have yet had the opportunity to have been vetted
heavily due to its very young age.
Alternatively, the individual(s) sharing the pattern may not have the time or interest of
going through the ‘pattern’-ity process and might release a short description of their
proto-pattern instead. Brief descriptions or snippets of this type of pattern are known
as patlets.
The work involved in fully documenting a qualified pattern can be quite daunting.
Looking back at some of the earliest work in the field of design patterns, a pattern may
be considered ‘good’ if it does the following:
7
• Solves a particular problem: Patterns are not supposed to just capture principles
or strategies. They need to capture solutions. This is one of the most essential
ingredients for a good pattern.
• The solution to this problem cannot be obvious: You can often find that prob-
lem-solving techniques attempt to derive from well-known first principles. The
best design patterns usually provide solutions to problems indirectly - this is con-
sidered a necessary approach for the most challenging problems related to design.
• The concept described must have been proven: Design patterns require proof
that they function as described and without this proof the design cannot be seri-
ously considered. If a pattern is highly speculative in nature, only the brave may
attempt to use it.
• It must describe a relationship: In some cases it may appear that a pattern de-
scribes a type of module. Although an implementation may appear this way, the
official description of the pattern must describe much deeper system structures
and mechanisms that explain its relationship to code.
We would be forgiven for thinking that a proto-pattern which fails to meet guidelines
isn't worth learning from, however, this is far from the truth. Many proto-patterns are
actually quite good. I’m not saying that all proto-patterns are worth looking at, but
there are quite a few useful ones in the wild that could assist you with future projects.
Use best judgment with the above list in mind and you’ll be fine in your selection
process.
One of the additional requirements for a pattern to be valid is that they display some
recurring phenomenon. This is often something that can be qualified in at least three
key areas, referred to as the rule of three. To show recurrence using this rule, one must
demonstrate:
1. Fitness of purpose - how is the pattern considered successful?
2. Usefulness- why is the pattern considered successful?
3. Applicability - is the design worthy of being a pattern because it has wider ap-
plicability? If so, this needs to be explained.When reviewing or defining a pattern,
it is important to keep the above in mind.
You may be curious about how a pattern author might approach outlining structure,
implementation and purpose of a new pattern. Traditionally, a pattern is initially be
presented in the form of a rule that establishes a relationship between:
• A context
• A system of forces that arises in that context and
• A configuration that allows these forces to resolve themselves in context
With this in mind, lets now take a look at a summary of the component elements for
a design pattern. A design pattern should have a:
• Pattern name and a description
• Context outline – the contexts in which the pattern is effective in responding to
the users needs.
• Problem statement – a statement of the problem being addressed so we can un-
derstand the intent of the pattern.
• Solution – a description of how the user’s problem is being solved in an under-
standable list of steps and perceptions.
• Design – a description of the pattern’s design and in particular, the user’s behavior
in interacting with it
• Implementation– a guide to how the pattern would be implemented
• Illustrations – a visual representation of classes in the pattern (e.g. a diagram))
• Examples – an implementation of the pattern in a minimal form
• Co-requisites – what other patterns may be needed to support use of the pattern
being described?
• Relations – what patterns does this pattern resemble? does it closely mimic any
others?
• Known usage – is the pattern being used in the ‘wild’?. If so, where and how?
• Discussions – the team or author’s thoughts on the exciting benefits of the pattern
9
Design patterns are quite a powerful approach to getting all of the developers in an
organization or team on the same page when creating or maintaining solutions. If you
or your company ever consider working on your own pattern, remember that although
they may have a heavy initial cost in the planning and write-up phases, the value re-
turned from that investment can be quite worth it. Always research thoroughly before
working on new patterns however, as you may find it more beneficial to use or build
on top of existing proven patterns than starting afresh.
Although this book is aimed at those new to design patterns, a fundamental under-
standing of how a design pattern is written can offer you a number of useful benefits.
For starters, you can gain a deeper appreciation for the reasoning behind a pattern being
needed. You can also learn how to tell if a pattern (or proto-pattern) is up to scratch
when reviewing it for your own needs.
Writing good patterns is a challenging task. Patterns not only need to provide a sub-
stantial quantity of reference material for end-users (such as the items found in the
structure section above), but they also need to be able to defend why they are necessary.
If you’ve already read the previous section on ‘what’ a pattern is, you may think that
this in itself should help you identify patterns when you see them in the wild. This is
actually quite the opposite - you can’t always tell if a piece of code you’re inspecting
follows a pattern.
When looking at a body of code that you think may be using a pattern, you might write
down some of the aspects of the code that you believe falls under a particular existing
pattern.In many cases of pattern-analysis you’ll find that you’re just looking at code
that follows good principles and design practices that could happen to overlap with the
rules for a pattern by accident. Remember - solutions in which neither interactions nor
defined rules appear are not patterns.
If you’re interested in venturing down the path of writing your own design patterns I
recommend learning from others who have already been through the process and done
it well. Spend time absorbing the information from a number of different design pattern
descriptions and books and take in what’s meaningful to you - this will help you ac-
complish the goals you have laid out for yours. Explore structure and semantics - this
can be done by examining the interactions and context of the patterns you are interested
in so you can identify the principles that assist in organizing those patterns together in
useful configurations.
Once you’ve exposed yourself to a wealth of information on pattern literature, you may
wish to begin your pattern using an existing format and see if you can brainstorm new
ideas for improving it or integrating your ideas in there. An example of someone that
11
did this is in recent years is Christian Heilmann, who took the existing module pattern
and made some fundamentally useful changes to it to create the revealing module pat-
tern (this is one of the patterns covered later in this book).
If you would like to try your hand at writing a design pattern (even if just for the learning
experience of going through the process), the tips I have for doing so would be as
follows:
• Bear in mind practicability: Ensure that your pattern describes proven solutions
to recurring problems rather than just speculative solutions which haven’t been
qualified.
• Ensure that you draw upon best practices: The design decisions you make
should be based on principles you derive from an understanding of best-practices.
• Your design patterns should be transparent to the user: Design patterns should
be entirely transparent to any type of user-experience. They are primarily there to
serve the developers using them and should not force changes to behavior in the
user-experience that would not be incurred without the use of a pattern.
• Remember that originality is not key in pattern design: When writing a pattern,
you do not need to be the original discoverer of the solutions being documented
nor do you have to worry about your design overlapping with minor pieces of other
patterns.If your design is strong enough to have broad useful applicability, it has
a chance of being recognized as a proper pattern
• Know the differences between patterns and design: A design pattern generally
draws from proven best practice and serves as a model for a designer to create a
solution. The role of the pattern is to give designers guidance to make the best design
choices so they can cater to the needs of their users.
• Your pattern needs to have a strong set of examples: A good pattern description
needs to be followed by an equally strong set of examples demonstrating the suc-
cessful application of your pattern. To show broad usage, examples that exhibit
good design principles are ideal.
Pattern writing is a careful balance between creating a design that is general, specific
and above all, useful. Try to ensure that if writing a pattern you cover the widest possible
areas of application and you should be fine. I hope that this brief introduction to writing
patterns has given you some insights that will assist your learning process for the next
sections of this book.
13
is parallel to the way in which design patterns provide us with a way to recognize
common techniques that are useful.
To summarize, an anti-pattern is a bad design that is worthy of documenting. Examples
of anti-patterns in JavaScript are the following:
• Polluting the global namespace by defining a large number of variables in the global
context
• Passing strings rather than functions to either setTimeout or setInterval as this
triggers the use of eval() internally.
• Modifying the Object class prototype (this is a particularly bad anti-pattern)
• Using JavaScript in an inline form as this is inflexible
• The use of document.write where native DOM alternatives such as document.cre-
ateElement are more appropriate. document.write has been grossly misused over
the years and has quite a few disadvantages including that if it's executed after the
page has been loaded it can actually overwrite the page you're on, whilst docu-
ment.createElement does not. You can see here for a live example of this in action.
It also doesn't work with XHTML which is another reason opting for more DOM-
friendly methods such as document.createElement is favorable.
Knowledge of anti-patterns is critical for success. Once you are able to recognize such
anti-patterns, you will be able to refactor your code to negate them so that the overall
quality of your solutions improves instantly.
14 | Chapter 6: Anti-Patterns
Random documents with unrelated
content Scribd suggests to you:
generale, intimamente vero, per la sorte di tutte le discipline
dell’intelletto: «L’arte, della quale parliamo non è amica del riposo e
della pace, non ama la probità e la moderazione..... Essa è figlia
della licenza, che gli stolti chiamano libertà, è compagna e ispiratrice
dei rivolgimenti pubblici: senza rispetti, incapace di servire, ribelle,
temeraria, arrogante, tale da non poter fiorire in una città bene
ordinata..... La vegetazione più vigorosa è figlia della terra, che non
ha mai subìto l’aratro...» [877].
SOMMARIO
INTRODUZIONE pag. 5
I. La monarchia Dioclezianea-Costantiniana e
il trasporto della capitale a Costantinopoli.
Ripercussione di ciò sulle sorti della
istruzione pubblica nell’impero. — II.
Costantino e la coltura. L’Università
Costantinopolitana. — III. Una nuova
biblioteca pubblica. Costantino e l’istruzione
professionale. L’istruzione primaria; fine
delle fondazioni alimentari. — IV. Privilegi e
garanzie ai docenti privati e pubblici nelle
città di provincia. Ampliamento delle
immunità e suoi motivi. Immunità ai
professionisti delle arti edilizie e industriali.
— V. Costantino e la cura delle opere
d’arte. — VI. I figli di Costantino ne
continuano la politica; gl’imperatori, il
Senato e i governatori nella scelta dei
maestri. Riforme nell’Università ateniese.
Dichiarazione dei nuovi criterii di governo in
fatto di istruzione pubblica. — VII. I figli di
Costantino e probabile limitazione delle
immunità.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com