Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: e255040d34
Fetching contributors…

Cannot retrieve contributors at this time

6874 lines (5469 sloc) 378.529 kB
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Essential JavaScript Design Patterns</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/shCore.css">
<link rel="stylesheet" type="text/css" href="css/shThemeRDark.css">
</head>
<body>
<div class="container">
<header>
<p>
<h1 class="booktitle">Essential JavaScript Design Patterns</h1>
<h2 class="booktitle">Volume 1.5.1</h2>
<p class="booktitle"><a href="https://twitter.com/share" class="twitter-share-button" data-url="http://addyosmani.com/resources/essentialjsdesignpatterns/book/" data-count="horizontal" data-via="addyosmani">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></p>
<p class="bookauthor">A book by <a href="http://www.twitter.com/addyosmani">Addy Osmani</a></p>
<p>&nbsp;</p>
<p class="copyright">
Copyright &copy; Addy Osmani 2012.
</p>
<p class="copyright">Creative Commons <a href="http://creativecommons.org/licenses/by-sa/3.0/us/">Attribution-NonCommercial-ShareAlike 3.0</a> unported license. You are free to remix, tweak, and build upon this work non-commercially, as long as you credit Addy Osmani (the copyright holder) and license your new creations under the identical terms. Any of the above conditions can be waived if you get permission from the copyright holder. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">link to the license</a>. </p>
<p class="copyright">&nbsp;</p>
</header>
<div class="content">
<h1><strong>Preface</strong></h1>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>In this book we will explore applying both classical and modern design patterns to the JavaScript programming language.</p>
<p>&nbsp;</p>
<h2>Target Audience</h2>
<p>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.</p>
<p>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.</p>
<p>If you would like to learn how to write beautiful, structured and organized code, I believe this is the book for you.</p>
<h2>Acknowledgements</h2>
<p>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 reviewer's tweets and blogs are also a regular source of both ideas and inspiration and I wholeheartedly recommend checking them out.</p>
<p>
<ul>
<li>Alex Sexton (<a href="http://alexsexton.com">http://alexsexton.com</a>, <a href="http://twitter.com/slexaxton">@slexaxton</a>)</li>
<li>Andrée Hansson (<a href="http://andreehansson.se/">http://andreehansson.se/</a>, <a href="http://twitter.com/peolanha">@peolanha</a>)</li>
</ul>
</p>
<p>I would also like to thank Rebecca Murphey (<a href="http://rebeccamurphey.com">http://rebeccamurphey.com</a>, <a href="http://twitter.com/rmurphey">@rmurphey</a>) for providing the inspiration to write this book and more importantly, continue to make it both available on GitHub and via O'Reilly.</p>
<p>Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was putting together this publication.</p>
<h2>Credits</h2>
<p>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 developers. Similar to Stoyan Stefanov's logical approach to preventing interruption of the narrative with credits (in <em>JavaScript Patterns</em>), I have listed credits and suggested reading for any content covered in the references section.</p>
<p>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.</p>
<h2>Reading</h2>
<p>
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 langage, I am happy to recommend the following titles:</p>
<ul>
<li><em>JavaScript: The Definitive Guide</em> by David Flanagan</li>
<li><em>Eloquent JavaScript</em> by Marijn Haverbeke</li>
<li><em>JavaScript Patterns</em> by Stoyan Stefanov</li>
<li><em>Writing Maintainable JavaScript</em> by Nicholas Zakas</li>
<li><em>JavaScript: The Good Parts</em> by Douglas Crockford</li>
</ul>
<p>&nbsp;</p>
<h1><em>Table Of Contents</em></h1>
<div id="contents-list">
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#whatisapattern">What is a Pattern?</a></li>
<li><a href="#patternity">'Pattern'-ity Testing, Proto-Patterns &amp; The Rule Of Three</a></li>
<li><a href="#designpatternstructure">The Structure Of A Design Pattern</a></li>
<li><a href="#writingdesignpatterns">Writing Design Patterns</a></li>
<li><a href="#antipatterns">Anti-Patterns</a></li>
<li><a href="#categoriesofdesignpatterns">Categories Of Design Pattern</a></li>
<li><a href="#summarytabledesignpatterns">Summary Table Of Design Pattern Categorization</a></li>
<li><a href="#designpatternsjavascript">An Introduction To Design Patterns
</a>
<ul>
<li class="subitem"><a href="#creationalpatternjavascript">Creational Pattern</a></li>
<li class="subitem"><a href="#constructorpatternjavascript">Constructor Pattern</a></li>
<li class="subitem"><a href="#singletonpatternjavascript">Singleton Pattern</a></li>
<li class="subitem"><a href="#modulepatternjavascript">Module Pattern</a></li>
<li class="subitem"><a href="#revealingmodulepatternjavascript">Revealing Module Pattern</a></li>
<li class="subitem"><a href="#observerpatternjavascript">Observer Pattern</a></li>
<li class="subitem"><a href="#mediatorpatternjavascript">Mediator Pattern</a></li>
<li class="subitem"><a href="#prototypepatternjavascript">Prototype Pattern</a></li>
<li class="subitem"><a href="#commandpatternjavascript">Command Pattern</a></li>
<li class="subitem"><a href="#drypatternjavascript">DRY Pattern</a></li>
<li class="subitem"><a href="#facadepatternjavascript">Facade Pattern</a></li>
<li class="subitem"><a href="#factorypatternjavascript">Factory Pattern</a></li>
<li class="subitem"><a href="#mixinpatternjavascript">Mixin Pattern</a>
<li class="subitem"><a href="#decoratorpatternjavascript">Decorator Pattern</a></li>
</ul>
</li>
<li><a href="#detailedpatterns">Patterns In Greater Detail</a></li>
<ul>
<li class="subitem"><a href="#detailedobserver">Observer (Publish/Subscribe)</a>
<li class="subitem"><a href="#detailmvcmvp">MVC &amp; MVP Structural Patterns</a>
<li class="subitem"><a href="#detaildecorator">Decorator Pattern</a>
<li class="subitem"><a href="#detailnamespacing">Namespacing Patterns</a>
<li class="subitem"><a href="#detailflyweight">Flyweight Pattern</a>
<li class="subitem"><a href="#detailmodule">Module Pattern</a>
</ul>
<li><a href="#designpatternsjquery">Examples Of Design Patterns In jQuery</a></li>
<ul>
<li class="subitem"><a href="#modulepatternjquery">Module Pattern</a>
<li class="subitem"><a href="#lazyinitialisationjquery">Lazy Initialisation</a></li>
<li class="subitem"><a href="#compositepatternjquery">Composite Pattern</a></li>
<li class="subitem"><a href="#wrapperpatternjquery">Wrapper Pattern</a></li>
<li class="subitem"><a href="#facadepatternjquery">Facade Pattern</a></li>
<li class="subitem"><a href="#observerpatternjquery">Observer Pattern</a></li>
<li class="subitem"><a href="#iteratorpatternjquery">Iterator Pattern</a></li>
<li class="subitem"><a href="#strategypatternjquery">Strategy Pattern</a></li>
<li class="subitem"><a href="#proxypatternjquery">Proxy Pattern</a></li>
<li class="subitem"><a href="#builderpatternjquery">Builder Pattern</a></li>
<li class="subitem"><a href="#prototypepatternjquery">Prototype Pattern</a></li>
</ul>
<li><a href="#modularjavascript">Modern Modular JavaScript Design Patterns</a></li>
<li><a href="#jquerypluginpatterns">Bonus: jQuery Plugin Design Patterns</a></li>
<li><a href="#conclusions">Conclusions</a></li>
<li><a href="#references">References</a></li>
</ul>
</div>
</p>
<h1 id="introduction"><strong>Introduction</strong></h1>
<p>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.</p>
<p>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 '<a href="#whatisapattern">What is a Pattern?</a>' to continue reading.</p>
<p>Design patterns can be traced back to the early work of a civil engineer named <a href="http://en.wikipedia.org/wiki/Christopher_Alexander">Christopher Alexander</a>. 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. </p>
<p>In collaboration with Sarah Ishikawra 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 <a href="http://www.amazon.co.uk/Pattern-Language-Buildings-Construction-Environmental/dp/0195019199/ref=sr_1_1?s=books&ie=UTF8&qid=1329440685&sr=1-1">book</a>. </p>
<p>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 programming industry since its inception, albeit in a less formalized form. </p>
<p>One of the first and arguably most iconic formal works published on design patterns in software engineering was a book in 1995 called <em>'Design Patterns: Elements Of Reusable Object-Oriented Software</em>'. This was written by <a href="http://en.wikipedia.org/wiki/Erich_Gamma">Erich Gamma</a>,<a href="http://en.wikipedia.org/w/index.php?title=Richard_Helm&action=edit&redlink=1"> Richard Helm</a>,<a href="http://en.wikipedia.org/wiki/Ralph_Johnson"> Ralph Johnson</a> and<a href="http://en.wikipedia.org/wiki/John_Vlissides"> John Vlissides</a> - a group that became known as the Gang of Four (or GoF for short). </p>
<p>The GoF's publication is considered quite instrumental to pushing the concept of design patterns further in our field as it describes a number of development techniques 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 &lsquo;Categories of Design Patterns&rsquo;.</p>
<p>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. Remember that patterns can be applied not just to vanilla JavaScript, but also to abstracted libraries such as jQuery or Dojo as well. Before we begin, let&rsquo;s look at the exact definition of a &lsquo;pattern&rsquo; in software design.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="whatisapattern">What is a Pattern?</h1>
<p>A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript-powered applications. Another way of looking at patterns are as templates for how you solve problems - ones which can be used in quite a few different situations.</p>
<p>So, why is it important to understand patterns and be familiar with them?. Design patterns have three main benefits: </p>
<ol start="1" type="1">
<ol>
<ol>
<li><strong>Patterns are proven solutions:</strong> They provide solid approaches to solving issues in software development using proven solutions that reflect the experience and insights the developers that helped define and improve them bring to the pattern.</li>
<li><strong>Patterns can be easily re-used: </strong>A pattern usually reflects an out of the box solution that can be adapted to suit your own needs. This feature makes them quite robust.</li>
<li><strong>Patterns can be expressive: </strong>When you look at a pattern there&rsquo;s generally a set structure and &lsquo;vocabulary&rsquo; to the solution presented that can help express rather large solutions quite elegantly.</li>
</ol>
</ol>
</ol>
<p>&nbsp;</p>
<p>Patterns are <strong>not</strong> an exact solution. It&rsquo;s important that we remember the role of a pattern is merely to provide us with a solution scheme. Patterns don&rsquo;t solve all design problems nor do they replace good software designers, however, they <strong>do</strong> support them. Next we&rsquo;ll take a look at some of the other advantages patterns have to offer. </p>
<ul>
<li><strong>Reusing patterns assists in preventing minor issues that can cause major problems in the application development process. </strong>What this means is when code is built on proven patterns, we can afford to spend less time worrying about the structure of our code and more time focusing on the quality of our overall solution. This is because patterns can encourage us to code in a more structured and organized fashion so the need to refactor it for cleanliness purposes in the future.</li>
</ul>
<ul>
<li><strong>Patterns can provide generalized solutions which are documented in a fashion that doesn't require them to be tied to a specific problem.</strong> This generalized approach means that regardless of the application (and in many cases the programming language) you are working with, design patterns can be applied to improve the structure of your code.</li>
<li><strong>Certain patterns can actually decrease the overall file-size footprint of your code by avoiding repetition. </strong>By encouraging developers to look more closely at their solutions for areas where instant reductions in <span id="internal-source-marker_0.982673292361492">repetition</span> 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. </li>
<li><strong>Patterns that are frequently </strong>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 improved 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.</li>
</ul>
<p>&nbsp;</p>
<h3>We already use patterns everyday</h3>
<p>
To understand how useful patterns can be, let's review a very simple selection problem that the jQuery library solves for us everyday. </p>
<p>
If we imagine that we have a script where for each DOM element on a page with class "foo" we want to increment a counter, what's the simplest efficient way to query for the list we need?. Well, there are a few different ways this problem could be tackled:</p>
<p>
<ol>
<li>Select all of the elements in the page and then store them. Next, filter this list and use regular expressions (or another means) to only store those with the class "foo".</li>
<li>
Use a modern native browser feature such as <code>querySelectorAll()</code> to select all of the elements with the class "foo".</li>
<li>Use a native feature such as <code>getElementsByClassName()</code> to similarly get back the desired list. </li>
</ol>
</p>
<p>
So, which of these is the fastest?. You might be interested to know that it's actually number 3 by a factor of 8-10 times the <a href="http://jsperf.com/getelementsbyclassname-vs-queryselectorall/5">alternatives</a>. In a real-world application however, 3. will not work in versions of Internet Explorer below 9 and thus it's necessary to use 1. where 3. isn't supported.</p>
<p>
Developers using jQuery don't have to worry about this problem, as it's luckily abstraced away for us. The library opts for the most optimal approach to selecting elements depending on what your browser supports.</p>
<p>It internally uses a number of different <strong>design patterns</strong>, the most frequent one being a facade, which provides a simple set of interfaces to a more complex body of code. We're probably all familiar with <code>$(elem)</code> (yes, it's a facade!), which is a lot easier to use than having to manually normalize cross-browser differences.</p>
<p>
We'll be looking at this and more design patterns later on in the book.</p>
<p>&nbsp;</p>
<h1 id="patternity">'Pattern'-ity Testing, Proto-Patterns &amp; The Rule Of Three</h1>
<p>
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.<br>
<br>
Looking back upon the work by Alexander once more, he claims that a pattern should both be a process and a &lsquo;thing&rsquo;. This definition is obtuse on purpose as he follows by saying that it is the process should create the &lsquo;thing&rsquo;. 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. <br>
<br>
In studying design patterns, you may come across the term &lsquo;proto-pattern&rsquo; quite frequently. What is this? Well, a pattern that has not yet been known to pass the &lsquo;pattern&rsquo;-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 it’s very young age.<br>
<br>
Alternatively, the individual(s) sharing the pattern may not have the time or interest of going through the &lsquo;pattern&rsquo;-ity process and might release a short description of their proto-pattern instead. Brief descriptions of this type of pattern are known as patlets.<br>
<br>
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 &lsquo;good&rsquo; if it does the following: </p>
<p>&nbsp;</p>
<ul type="disc">
<li><strong>Solves a particular problem</strong>: 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.</li>
<li><strong>The solution to this problem cannot be obvious </strong>: You can often find that problem-solving techniques attempt to derive from well-known first principles. The best design patterns usually provide solutions to problems indirectly - this is considered a necessary approach for the most challenging problems related to design.</li>
<li><strong>The concept described must have been proven</strong>: Design patterns require proof that they function as described and without this proof the design cannot be seriously considered. If a pattern is highly speculative in nature, only the brave may attempt to use it.</li>
<li><strong>It must describe a relationship </strong>: In some cases it may appear that a pattern describes 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 it&rsquo;s relationship to code.</li>
</ul>
<p><br>
<br>
You wouldn&rsquo;t be blamed for thinking that a proto-pattern which doesn&rsquo;t meet the guidelines is worth learning from at all, but this is far from the truth. Many proto-patterns are actually quite good. I&rsquo;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&rsquo;ll be fine in your selection process. <br>
<br>
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 <em>rule of three</em>. To show recurrence using this rule, one must demonstrate: </p>
<p>&nbsp;</p>
<ol start="1" type="1">
<li><strong>Fitness of purpose</strong> - how is the pattern considered successful?</li>
<li><strong>Usefulness </strong>- why is the pattern considered successful?</li>
<li><strong>Applicability</strong> - is the design worthy of being a pattern because it has wider applicability? If so, this needs to be explained.When reviewing or defining a pattern, it is important to keep the above in mind.</li>
</ol>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="designpatternstructure">The Structure Of A Design Pattern</h1>
<p>When studying design patterns, you may wonder what teams that create them have to put in their design pattern descriptions.&nbsp; Every pattern has to initially be formulated in a form of a <strong>rule</strong> that establishes a relationship between a <strong>context</strong>, a system of <strong>forces</strong> that arises in that context and a <strong>configuration</strong> that allows these forces to resolve themselves in context.&nbsp; </p>
<p>&nbsp;</p>
<p>I find that a lot of the information available out there about the structure of a good pattern can be condensed down to something more easily digestible.With this in mind, lets now take a look at a summary of the component elements for a design pattern.</p>
<p>&nbsp;</p>
<p><strong>A design pattern must have a:</strong></p>
<ul>
<li><strong>Pattern Name</strong> and a <strong>description </strong></li>
<li><strong>Context Outline</strong> – the contexts in which the pattern is effective in responding to the users needs. </li>
<li><strong>Problem Statement</strong> – a statement of the problem being addressed so we can understand the intent of the pattern. </li>
<li><strong>Solution</strong> – a description of how the user&rsquo;s problem is being solved in an understandable list of steps and perceptions. </li>
<li><strong>Design</strong> – a description of the pattern&rsquo;s design and in particular, the user&rsquo;s behavior in interacting with it </li>
<li><strong>Implementation </strong>– a guide to how the pattern would be implemented </li>
<li><strong>Illustrations</strong> – a visual representation of classes in the pattern (eg. a diagram)) </li>
<li><strong>Examples</strong> – an implementation of the pattern in a minimal form </li>
<li><strong>Co-requisites</strong> – what other patterns may be needed to support use of the pattern being described? </li>
<li><strong>Relations</strong> – what patterns does this pattern resemble? does it closely mimic any others? </li>
<li><strong>Known usage</strong> – is the pattern being used in the &lsquo;wild&rsquo;?. If so, where and how? </li>
<li><strong>Discussions</strong> – the team or author&rsquo;s thoughts on the exciting benefits of the pattern </li>
</ul>
<p>&nbsp;</p>
<p>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 returned 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.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="writingdesignpatterns">Writing Design Patterns</h1>
<p>Although this book is aimed at those new to design patterns, a fundamental understanding 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 but can also learn how to tell if a pattern (or proto-pattern) is up to scratch when reviewing it for your own needs.<br>
<br>
Writing good patterns is a challenging task. Patterns not only need to provide a substantial quantity of reference material for end-users (such as the items found in the <em>structure</em> section above), but they also need to be able to almost tell a &lsquo;story&rsquo; that describes the experience they are trying to convey. If you&rsquo;ve already read the previous section on &lsquo;what&rsquo; 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&rsquo;t always tell if a piece of code you&rsquo;re inspecting follows a pattern.<br>
<br>
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, but it may not be a one at all. In many cases of pattern-analysis you&rsquo;ll find that you&rsquo;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. <br>
<br>
If you&rsquo;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&rsquo;s meaningful to you - this will help you accomplish the goals you&rsquo;ve got of designing the pattern you want to achieve. You&rsquo;ll probably also want to examine the structure and semantics of existing patterns - this can be begun 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.<br>
<br>
Once you&rsquo;ve exposed yourself to a wealth of information on pattern literature, you may wish to begin your pattern using an <em>existing</em> format and see if you can brainstorm new ideas for improving it or integrating your ideas in there. &nbsp;An example of someone that did this quite recently is JavaScript developer Christian Heilmann, who took an existing pattern called the <em>module</em> pattern and made some fundamentally useful changes to it to create the <em>revealing module</em> pattern (this is one of the patterns covered later in this book). <br>
<br>
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:</p>
<p>&nbsp;</p>
<ul type="disc">
<li><strong>Bear in mind practicability</strong>: Ensure that your pattern describes proven solutions to recurring problems rather than just speculative solutions which haven&rsquo;t been qualified.</li>
<li><strong>Ensure that you draw upon best practices:</strong> The design decisions you make should be based on principles you derive from an understanding of best practices. </li>
<li><strong>Your design patterns should be transparent to the user</strong>: 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 behaviour in the user-experience that would not be incurred without the use of a pattern.</li>
<li><strong>Remember that originality is <em>not</em> key in pattern design</strong>: 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</li>
<li><strong>Know the differences between patterns and design</strong>: A design pattern generally draws from proven best practice and serves as a model for a designer to create a solution<em>. 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.</em></li>
<li><strong>Your pattern needs to have a strong set of examples:</strong> A good pattern description needs to be followed by an equally strong set of examples demonstrating the successful application of your pattern. To show broad usage, examples that exhibit good design principles are ideal.</li>
</ul>
<p>&nbsp;</p>
<p><br>
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. &nbsp;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. </p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="antipatterns">Anti-Patterns</h1>
<p>If we consider that a pattern represents a best practice, an anti-pattern represents a lesson that has been learned. The term anti-patterns was coined in 1995 by Andrew Koenig in the November C++ Report that year, inspired by the GoF's book <em>Design Patterns</em>. In Koenig&rsquo;s report, there are two notions of anti-patterns that are presented. Anti-Patterns: </p>
<ul type="disc">
<li>Describe a<em> bad</em> solution to a particular problem which resulted in a bad situation occurring </li>
<li>Describe <em>how</em> to get out of said situation and how to go from there to a good solution </li>
</ul>
<p><br>
<br>
On this topic, Alexander writes about the difficulties in achieving a good balance between good design structure and good context:<br>
<br>
<em>&ldquo;These notes are about the process of design; the process of inventing physical things which display a new physical order, organization, form, in response to function.…every design problem begins with an effort to achieve fitness between two entities: the form in question and its context. The form is the solution to the problem; the context defines the problem&rdquo;.</em><br>
<br>
While it&rsquo;s quite important to be aware of design patterns, it can be equally important to understand anti-patterns. Let us qualify the reason behind this. When creating an application, a project&rsquo;s life-cycle begins with construction however once you&rsquo;ve got the initial release done, it needs to be maintained. The quality of a final solution will either be <em>good</em> or <em>bad</em>, depending on the level of skill and time the team have invested in it. Here <em>good</em> and <em>bad</em> are considered in context - a &lsquo;perfect&rsquo; design may qualify as an anti-pattern if applied in the wrong context. <br>
<br>
The bigger challenges happen after an application has hit production and is ready to go into maintenance mode. A developer working on such a system who hasn&rsquo;t worked on the application before may introduce a <em>bad</em> design into the project by accident. If said <em>bad</em> practices are created as anti-patterns, they allow developers a means to recognize these in advance so that they can avoid common mistakes that can occur - this is parallel to the way in which design patterns provide us with a way to recognize common techniques that are <em>useful.</em> <br>
<br>
To summarize, an anti-pattern is a bad design that is worthy of documenting. Examples of anti-patterns in JavaScript are the following: </p>
<ul type="disc">
<li>Polluting the namespace by defining a large number of variables in the global context</li>
<li>Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of eval() internally.</li>
<li>Prototyping against the Object object (this is a particularly bad anti-pattern)</li>
<li>Using JavaScript in an inline form as this is inflexible </li>
<li>The use of document.write where native DOM alternatives such as document.createElement 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 document.createElement does not. You can see <a href="http://jsfiddle.net/addyosmani/6T9vX/">here</a> 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.</li>
</ul>
<p>&nbsp;</p>
<p><br>
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. </p>
<p>&nbsp;</p>
<h1 id="categoriesofdesignpatterns">Categories Of Design Pattern</h1>
<p>&nbsp;</p>
<p>A glossary from the well-known design book, <em>Domain-Driven Terms, </em>rightly states that:</p>
<h3>&ldquo;A design pattern names, abstracts, and identifies the key aspects of a common design structure that make it useful for creating a reusable object-oriented design. The design pattern identifies the participating classes and their instances, their roles and collaborations, and the distribution of responsibilities. </h3>
<h3>Each design pattern focuses on a particular object-oriented design problem or issue. It describes when it applies, whether or not it can be applied in view of other design constraints, and the consequences and trade-offs of its use. Since we must eventually implement our designs, a design pattern also provides sample ... code to illustrate an implementation. </h3>
<h3>Although design patterns describe object-oriented designs, they are based on practical solutions that have been implemented in mainstream object-oriented programming languages ....&rdquo;</h3>
<p>&nbsp;</p>
<p>Design patterns can be broken down into a number of different categories. In this section we&rsquo;ll review three of these categories and briefly mention a few examples of the patterns that fall into these categories before exploring specific ones in more detail.
</p>
<h2><br>
Creational Design Patterns</h2>
<p><br>
Creational design patterns focus on handling object creation mechanisms where objects are created in a manner suitable for the situation you are working in. The basic approach to object creation might otherwise lead to added complexity in a project whilst creational patterns aim to solve this problem by <em>controlling</em> the creation of such objects.<br>
<br>
Some of the patterns that fall under this category are: Factory, Abstract, Prototype, Singleton and Builder.</p>
<p>&nbsp;</p>
<h2>Structural Design Patterns</h2>
<p><em><br>
</em>Structural patterns focus on the composition of classes and objects. Structural &lsquo;class&rsquo; creation patterns use inheritance to compose interfaces whilst &lsquo;object&rsquo; patterns define methods to create objects to obtain new functionality. <br>
<br>
Patterns that fall under this category include: Decorator, Facade, Composite, Adapter and Bridge</p>
<p>&nbsp;</p>
<h2>Behavioral Design Patterns<br>
<br>
</h2>
<p>The main focus behind this category of patterns is the communication between a class&rsquo;s objects. By specifically targeting this problem, these patterns are able to increase the flexibility in carrying out this communication.<br>
<br>
Some behavioral patterns include: Iterator, Mediator, Observer and Visitor.</p>
<p>&nbsp;</p>
<h1 id="summarytabledesignpatterns">Summary Table Of Design Pattern Categorization</h1>
<p>In my early experiences of learning about design patterns, I personally found the following table a very useful reminder of what a number of patterns has to offer - it covers the 23 Design Patterns mentioned by the GoF. The original table was summarized by Elyse Nielsen back in 2004
and I've modified it where necessary to suit our discussion in this section of the book.
<p>I recommend using this table as reference, but do remember that there are a number of additional patterns that are not mentioned here but will be discussed later in the book.</p>
<h3>A brief note on classes</h3>
<p>Keep in mind that there will be patterns in this table that reference the concept of 'classes'. JavaScript is a class-less language, however classes can be simulated using functions.</p>
<p>The most common approach to achieving this is by defining a JavaScript function where we then create an object using the <code>new</code> keyword. <code>this</code> can be used to help define new properties and methods for the object as follows:</p>
<pre class="brush: js">
// A car 'class'
function Car ( model ){
this.model = model;
this.color = 'silver';
this.year = '2012';
this.getInfo = function(){
return this.model + ' ' + this.year;
}
}
</pre>
<p>We can then instantiate the object using the Car constructor we defined above like this:</p>
<pre class="brush: js" >
var myCar = new Car('ford');
myCar.year = '2010';
console.log(myCar.getInfo());
</pre>
<p>For more ways to define 'classes' using JavaScript, see Stoyan Stefanov's useful <a href="http://www.phpied.com/3-ways-to-define-a-javascript-class/">post</a> on them.</p>
<p>Let us now proceed to review the table.
<p><br>
<p>
<table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" bgcolor="white">
<tbody><tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Creational </b></strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the concept of creating an object.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Factory Method </em></td>
<td colspan="3">This makes an instance of several derived classes based on interfaced data or events.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Abstract Factory </em></td>
<td colspan="3">Creates an instance of several families of classes without detailing concrete classes. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Builder</em></td>
<td colspan="3">Separates object construction from its representation, always creates the same type of object. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prototype</em></td>
<td colspan="3">A fully initialized instance used for copying or cloning. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Singleton</em></td>
<td colspan="3">A class with only a single instance with global access points. </td>
</tr>
<tr>
<td height="20" width="6">&nbsp;</td>
<td width="6">&nbsp;</td>
<td width="6">&nbsp;</td>
<td width="139">&nbsp;</td>
<td width="1">&nbsp;</td>
<td width="18">&nbsp;</td>
<td width="18">&nbsp;</td>
<td width="681">&nbsp;</td>
</tr>
<tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Structural </b> </strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the idea of building blocks of objects </td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adapter</em></td>
<td colspan="3"> Match interfaces of different classes therefore classes can work together despite incompatible interfaces </td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adapter</em></td>
<td colspan="3"> Match interfaces of different classes therefore classes can work together despite incompatible interfaces </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bridge</em></td>
<td colspan="3">Separates an object's interface from its implementation so the two can vary independently</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Composite</em></td>
<td colspan="3"> A structure of simple and composite objects which makes the total object more than just the sum of its parts.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Decorator</em></td>
<td colspan="3"> Dynamically add alternate processing to objects.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Facade</em></td>
<td colspan="3"> A single class that hides the complexity of an entire subsystem.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Flyweight</em></td>
<td colspan="3"> A fine-grained instance used for efficient sharing of information that is contained elsewhere. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Proxy</em></td>
<td colspan="3"> A place holder object representing the true object </td>
</tr>
<tr>
<td colspan="8">&nbsp;</td>
</tr>
<tr bgcolor="#fff">
<td colspan="4"><strong>&nbsp;&nbsp;<b>Behavioral </b></strong></td>
<td colspan="4">&nbsp;&nbsp;Based on the way objects play and work together.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Class </strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Interpreter</em></td>
<td colspan="3"> A way to include language elements in an application to match the grammer of the intended language. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Template <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Method </em></td>
<td colspan="3">Creates the shell of an algorithm in a method, then defer the exact steps to a subclass.</td>
</tr>
<tr bgcolor="#DBDBDB">
<td colspan="8"><em><strong>&nbsp;&nbsp;&nbsp;&nbsp;Object</strong></em></td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Chain of <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Responsibility </em></td>
<td colspan="3"> A way of passing a request between a chain of objects to find the object that can handle the request. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Command</em></td>
<td colspan="3"> Encapsulate a command request as an object to enable, logging and/or queuing of requests, and provides error-handling for unhandled requests. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Iterator</em></td>
<td colspan="3"> Sequentially access the elements of a collection without knowing the inner workings of the collection.</td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mediator</em></td>
<td colspan="3"> Defines simplified communication between classes to prevent a group of classes from referring explicitly to each other. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Memento</em></td>
<td colspan="3"> Capture an object's internal state to be able to restore it later. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Observer</em></td>
<td colspan="3"> A way of notifying change to a number of classes to ensure consistency between the classes. </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State</em></td>
<td colspan="3"> Alter an object's behavior when its state changes </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Strategy</em></td>
<td colspan="3"> Encapsulates an algorithm inside a class separating the selection from the implementation </td>
</tr>
<tr bgcolor="#F9F9F9">
<td colspan="5"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Visitor</em></td>
<td colspan="3"> Adds a new operation to a class without changing the class </td>
</tr>
</tbody></table></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="designpatternsjavascript">An Introduction To Design Patterns</h1>
<p>&nbsp;</p>
<p>We are now going to explore JavaScript implementations of a number of both classical and modern design patterns. This section of the book will cover an introduction to these patterns, whilst the next section will focus on looking at some select patterns in greater detail.</p>
<p>A common question developers regularly ask is what the 'ideal' set of patterns they should be using are. There isn't a singular answer to this question, but with the aid of what you'll learn in this book, you will hopefully be able to use your best judgement to select the right patterns to best suit your project's needs.</p>
<p>&nbsp;</p>
<p><strong>The patterns we will be exploring in this section are the:</strong></p>
<ul>
<li class="subitem"><a href="#creationalpatternjavascript">Creational Pattern</a></li>
<li class="subitem"><a href="#constructorpatternjavascript">Constructor Pattern</a></li>
<li class="subitem"><a href="#singletonpatternjavascript">Singleton Pattern</a></li>
<li class="subitem"><a href="#modulepatternjavascript">Module Pattern</a></li>
<li class="subitem"><a href="#revealingmodulepatternjavascript">Revealing Module Pattern</a></li>
<li class="subitem"><a href="#observerpatternjavascript">Observer Pattern</a></li>
<li class="subitem"><a href="#mediatorpatternjavascript">Mediator Pattern</a></li>
<li class="subitem"><a href="#prototypepatternjavascript">Prototype Pattern</a></li>
<li class="subitem"><a href="#commandpatternjavascript">Command Pattern</a></li>
<li class="subitem"><a href="#drypatternjavascript">DRY Pattern</a></li>
<li class="subitem"><a href="#facadepatternjavascript">Facade Pattern</a></li>
<li class="subitem"><a href="#factorypatternjavascript">Factory Pattern</a></li>
<li class="subitem"><a href="#mixinpatternjavascript">Mixin Pattern</a>
<li class="subitem"><a href="#decoratorpatternjavascript">Decorator Pattern</a></li>
</ul>
<p>&nbsp;</p>
<h2 id="creationalpatternjavascript">The Creational Pattern</h2>
<p>The Creational pattern is the basis for a number of the other design patterns we'll be looking at in this section and is probably the easiest to understand. As you may guess, the creational pattern deals with the idea of <em>creating</em> new things, specifically new objects. In JavaScript, the common way of creating new objects (collections of name/value) pairs is as follows:</p>
<p>Each of the following options will create a new empty object:</p>
<p><pre class="brush: js">
var newObject = {}; // or
var newObject = Object.create(null); // or
var newObject = new Object();
</pre></p>
<p>Where the 'Object' constructor creates an object wrapper for a specific value, or where no value is passed, it will create an empty object and return it.</p>
<p>There are then a number of ways in which keys and values can then be assigned to an object including:</p>
<p><pre class="brush: js">
newObject.someKey = 'Hello World';
newObject['someKey'] = 'Hello World';
// which can be accessed in a similar fashion
var key = newObject.someKey; //or
var key = newObject['someKey'];
</pre></p>
<p>We can also define new properties on objects as follows, should we require more granular configuration capabilities:</p>
<p><pre class="brush: js">
// First, define a new Object 'man'
var man = Object.create(null);
// Next let's create a configuration object containing properties
// Properties can be writable, enumerable and configurable
var config = {
writable: true,
enumerable: true,
configurable: true
};
// Typically one would use Object.defineProperty() to add new
// properties. For convenience we will use a short-hand version:
var defineProp = function ( obj, key, value ){
config.value = value;
Object.defineProperty(obj, key, config);
}
defineProp( man, 'car', 'Delorean' );
defineProp( man, 'dob', '1981' );
defineProp( man, 'beard', false );
</pre></p>
<p>As we will see a little later in the book, this can even be used for inheritance, as follows:</p>
<p><pre class="brush: js">
var driver = Object.create( man );
defineProp (driver, 'topSpeed', '100mph');
driver.topSpeed // 100mph
</pre></p>
<p>Thanks to Yehuda Katz for the less verbose version presented above.</p>
<p>&nbsp;</p>
<h2 id="constructorpatternjavascript">The Constructor Pattern</h2>
<p>The phrase &lsquo;constructor&rsquo; is familiar to most developers, however if you&rsquo;re a beginner it can be useful to review what a constructor is before we get into talking about a pattern dedicated to it.</p>
<p> Constructors are used to create specific types of objects - they both prepare the object for use and can also accept parameters which the constructor uses to set the values of member variables when the object is first created. The idea that a constructor is a paradigm can be found in the majority of programming languages, including JavaScript. You&rsquo;re also able to define custom constructors that define properties and methods for your own types of objects. <br></p>
<h3>Basic Constructors</h3>
<p>In JavaScript, constructor functions are generally considered a reasonable way to implement instances. As we saw earlier, JavaScript doesn't support the concept of classes but it does support special constructor functions. By simply prefixing a call to a constructor function with the keyword 'new', you can tell JavaScript you would like function to behave like a constructor and instantiate a new object with the members defined by that function.Inside a constructor, the keyword 'this' references the new object that's being created. Again, a very basic constructor may be:</p>
<p><pre class="brush: js">
function Car( model, year, miles ){
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function(){
return this.model + " has done " + this.miles + " miles";
};
}
var civic = new Car( "Honda Civic" , 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010 , 5000 );
console.log(civic.toString());
console.log(mondeo.toString());
</pre></p>
<p>The above is a simple version of the constructor pattern but it does suffer from some problems. One is that it makes inheritance difficult and the other is that functions such as toString() are redefined for each of the new objects created using the Car constructor. This isn't very optimal as the function should ideally be shared between all of the instances of the Car type.</p>
<p>&nbsp;</p>
<h3>Constructors With Prototypes</h3>
<p>Functions in JavaScript have a property called a prototype. When you call a JavaScript constructor to create an object, all the properties of the constructor's prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:
</p>
<p><pre class="brush: js">
function Car( model, year, miles ){
this.model = model;
this.year = year;
this.miles = miles;
}
/*
Note here that we are using Object.prototype.newMethod rather than
Object.prototype so as to avoid redefining the prototype object
*/
Car.prototype.toString = function(){
return this.model + " has done " + this.miles + " miles";
};
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());
</pre></p>
<p>Here, a single instance of toString() will now be shared between all of the Car objects.</p>
<p>Note: <a href="http://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a> recommends capitalizing your constructor functions so that it is easier to distinguish between them and normal functions.</p>
<h2>&nbsp;</h2>
<h2 id="singletonpatternjavascript">The Singleton Pattern</h2>
<p>In conventional software engineering, the singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.</p>
<p>The singleton pattern is thus known because traditionally, it restricts instantiation of a class to a single object. With JavaScript, singletons serve as a namespace provider which isolate implementation code from the global namespace so-as to provide a single point of access for functions.</p>
<p>The singleton doesn't provide a way for code that doesn't know about a previous reference to the singleton to easily retrieve it - it is not the object or 'class' that's returned by a singleton, it's a structure. Think of how closured variables aren't actually closures - the function scope that provides the closure is the closure.</p>
<p>
Singletons in JavaScript can take on a number of different forms and researching this pattern online is likely to result in at least 10 different variations. In its simplest form, a singleton in JS can be an object literal grouped together with its related methods and properties as follows:
<p>
<pre class="brush: js">
var mySingleton = {
property1: "something",
property2: "something else",
method1:function(){
console.log('hello world');
}
};
</pre>
</p>
<p>
If you wished to extend this further, you could add your own private members and methods to the singleton by encapsulating variable and function declarations inside a closure. Exposing only those which you wish to make public is quite straight-forward from that point as demonstrated below:</p>
<pre class="brush: js">
var mySingleton = function(){
// here are our private methods and variables
var privateVariable = 'something private';
function showPrivate(){
console.log( privateVariable );
}
// public variables and methods (which can access
// private variables and methods )
return {
publicMethod:function(){
showPrivate();
},
publicVar:'the public can see this!'
};
};
var single = mySingleton();
single.publicMethod(); // logs 'something private'
console.log( single.publicVar ); // logs 'the public can see this!'
</pre>
</p>
<p>
The above example is great, but let's next consider a situation where you only want to instantiate the singleton when it's needed. To save on resources, you can place the instantiation code inside another constructor function as follows:
<pre class="brush: js">
var Singleton = (function(){
var instantiated;
function init (){
// singleton here
return {
publicMethod: function(){
console.log( 'hello world' );
},
publicProperty: 'test'
};
}
return {
getInstance: function(){
if ( !instantiated ){
instantiated = init();
}
return instantiated;
}
};
})();
// calling public methods is then as easy as:
Singleton.getInstance().publicMethod();
</pre>
</p>
<p>&nbsp;</p>
<p>So, where else is the singleton pattern useful in practice?. Well, it's quite useful when exactly one object is needed to coordinate patterns across the system.&nbsp; Here's one last example of the singleton pattern being used:</p>
<p>&nbsp;</p>
<p>
<pre class="brush: js">
var SingletonTester = (function(){
// args: an object containing arguments for the singleton
  function Singleton( args ) {
// set args variable to args passed or empty object if none provided.
    var args = args || {};
//set the name parameter
    this.name = 'SingletonTester';
//set the value of pointX
    this.pointX = args.pointX || 6; //get parameter from arguments or set default
//set the value of pointY
    this.pointY = args.pointY || 10;  
  }
 
// this is our instance holder
  var instance;
// this is an emulation of static variables and methods
  var _static = {
    name: 'SingletonTester',
// This is a method for getting an instance
// It returns a singleton instance of a singleton object
    getInstance: function ( args ){
      if (instance === undefined) {
        instance = new Singleton( args );
      }
      return instance;
    }
  };
  return _static;
})();
var singletonTest = SingletonTester.getInstance({pointX: 5});
console.log(singletonTest.pointX); // outputs 5
</pre></p>
<p>&nbsp;</p>
<h2 id="modulepatternjavascript">The Module Pattern</h2>
<p>Let's now look at the popular <em>module</em> pattern. Note that we'll be covering this pattern in greater detail in the next section of the book, but a basic introduction to it will be given in this chapter.</p>
<p>The module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.</p>
<p>
In JavaScript, the module pattern is used to further <em>emulate</em> the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of your function names conflicting with other functions defined in additional scripts on the page.</p>
<p>JavaScript as a language doesn't have access modifiers that would allow us to implement true privacy, but for the purposes of most use cases, simulated privacy should work fine.</p>
<p>
Exploring the concept of public and private methods further, the module pattern pattern allows us to have particular methods and variables which are only accessible from within the module, meaning that you have a level of shielding from external entities accessing this 'hidden' information.</p>
<p> Let's begin looking at an implementation of the module pattern by creating a module which is self-contained. Here, other parts of the code are unable to directly read the value of our <code>incrementCounter()</code> or <code>resetCounter()</code>. The counter variable is actually fully shielded from our global scope so it acts just like a private variable would - its existence is limited to within the module's closure so that the only code able to access its scope are our two functions. Our methods are effectively namespaced so in the test section of our code, we need to prefix any calls with the name of the module (eg. 'testModule').
</p>
<p>
<pre class="brush: js">
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
// test
testModule.incrementCounter();
testModule.resetCounter();
</pre>
</p>
<p>When working with the module pattern, you may find it useful to define a simple template that you use for getting started with it. Here's one that covers namespacing, public and private variables:
</p>
<p>
<pre class="brush: js">
var myNamespace = (function(){
var myPrivateVar = 0;
var myPrivateMethod = function( someText ){
console.log(someText);
};
return {
myPublicVar: "foo",
myPublicFunction: function(bar){
myPrivateVar++;
myPrivateMethod(bar);
}
};
})();
</pre>
</p>
<p>A piece of trivia is that the module pattern was originally defined by Douglas Crockford (famous for his book 'JavaScript: The Good Parts, and more), although it is likely that variations of this pattern were used long before this. Another piece of trivia is that if you've ever played with Yahoo's YUI library, some of its features may appear quite familiar and the reason for this is that the module pattern was a strong influence for YUI when creating their components.</p>
<p><strong>Advantages:</strong> We've seen why the singleton pattern can be useful, but why is the module pattern a good choice? For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective. Secondly, it supports private data - so, in the module pattern, public parts of your code are able to touch the private parts, however the outside world is unable to touch the class's private parts (no laughing! Oh, and thanks to David Engfer for the joke).</p>
<p><strong>Disadvantages:</strong> The disadvantages of the module pattern are that as you access both public and private members differently, when you wish to change visibility, you actually have to make changes to each place the member was used. You also can't access private members in methods that are added to the object at a later point. That said, in many cases the module pattern is still quite useful and when used correctly, certainly has the potential to improve the structure of your application. Here's a final module pattern example:</p>
<p>
<pre class="brush: js">
var someModule = (function(){
// private attributes
  var privateVar = 5;
// private methods
  var privateMethod = function(){
   return 'Private Test';
  };
  return {
// public attributes
publicVar: 10,
// public methods
publicMethod: function(){
return ' Followed By Public Test ';
},
// let's access the private members
getData: function(){
return privateMethod() + this.publicMethod() + privateVar;
    }
  }
})(); //the parens here cause the anonymous function to execute and return
        
someModule.getData();
</pre></p>
<p>To continue reading more about the module pattern, I strongly recommend <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">Ben Cherry's JavaScript Module Pattern In-Depth</a> article.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="revealingmodulepatternjavascript">The Revealing Module Pattern</h2>
<p>Now that we're a little more familiar with the Module pattern, let&rsquo;s take a look at a slightly improved version - Christian Heilmann&rsquo;s Revealing Module pattern.</p>
<p>The Revealing Module Pattern came about as Heilmann (now at Mozilla) was frustrated with the fact that if you had to repeat the name of the main object when you wanted to call one public method from another or access public variables.&nbsp; He also disliked the Module pattern&rsquo;s requirement for having to switch to object literal notation for the things you wished to make public. </p>
<p>The result of his efforts were an updated pattern where you would simply define all of your functions and variables in the private scope and return an anonymous object at the end of the module along with pointers to both the private variables and functions you wished to reveal as public.</p>
<p>Once again, you&rsquo;re probably wondering what the benefits of this approach are. The Revealing Module Pattern allows the syntax of your script to be fairly consistent - it also makes it very clear at the end which of your functions and variables may be accessed publicly, something that is quite useful. In addition, you are also able to reveal private functions with more specific names if you wish.</p>
<p>An example of how to use the revealing module pattern can be found below:</p>
<p>
<pre class="brush: js">
 var myRevealingModule = (function(){
    var name = 'John Smith';
    var age = 40;
    function updatePerson(){
      name = 'John Smith Updated';
    }
    function setPerson () {
       name = 'John Smith Set';
    }
    function getPerson () {
       return name;
    }
    return {
        set: setPerson,
        get: getPerson
    };
}());
// Sample usage:
myRevealingModule.get();
</pre></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="observerpatternjavascript">The Observer Pattern</h2>
<p>The Observer pattern (also known as the Publish/Subscribe model) is a design pattern which allows an object (known as an observer) to watch another object (the subject) where the pattern provides a means for the subject and observer to form a publish-subscribe relationship. It is regularly used when we wish to decouple the different parts of an application from one another.</p>
<p>Note that this is another pattern we'll be looking at in greater detail in the next section of the book.</p>
<p>Observers are able to register (subscribe) to receive notifications from the subject when something interesting happens. When the subject needs to notify observers about interesting events, it broadcasts (publishes) a notification of these events to each observer (which can include data related to the event). .</p>
<p>The motivation behind using the observer pattern is where you need to maintain consistency between related objects without making classes tightly coupled. For example, when an object needs to be able to notify other objects without making assumptions regarding those objects. Another use case is where abstractions have more than one aspect, where one depends on the other. The encapsulation of these aspects in separate objects allows the variation and re-use of the objects independently. </p>
<p>
<strong>Advantages using the observer pattern include:</strong>
<ul>
<li>Support for simple broadcast communication. Notifications are broadcast automatically to all objects that have subscribed.</li>
<li>Dynamic relationships may exist between subjects and observers which can be easily established on page load. This provides a great deal of flexibility.</li>
<li>Abstract coupling between subjects and observers where each can be extended and re-used individually.</li>
</ul>
</p>
<strong>Disadvantages</strong>
<p>A draw-back of the pattern is that observers are ignorant to the existence of each other and are blind to the cost of switching in subject. Due to the dynamic relationship between subjects and observers the update dependency can be difficult to track.</p>
<p>Let us now take a look at an example of the observer pattern implemented in JavaScript. The following demo is a minimalist version of Pub/Sub I released on GitHub under a project called <a href="http://github.com/addyosmani/pubsubz">pubsubz</a>. Sample usage of this implementation can be seen shortly.</p>
<p>
<h3>Observer implementation</h3>
<p>
<pre class="brush: js">
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
// Publish or broadcast events of interest
// with a specific topic name and arguments
// such as the data to pass along
q.publish = function( topic, args ) {
if ( !topics[topic] ) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
// Subscribe to events of interest
// with a specific topic name and a
// callback function, to be executed
// when the topic/event is observed
q.subscribe = function( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
// Unsubscribe from a specific
// topic, based on a tokenized reference
// to the subscription
q.unsubscribe = function( token ) {
for ( var m in topics ) {
if ( topics[m] ) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
}( pubsub ));
</pre>
</p>
</p>
<p>
<h3>Observing and broadcasting</h3>
<p>We can now use the implementation to publish and subscribe to events of interest as follows:</p>
<p>
<pre class="brush: js">
var testSubscriber = function( topics , data ){
console.log( topics + ": " + data );
};
// Publishers are in charge of "publishing" notifications about events
pubsub.publish( 'example1', 'hello world!' );
pubsub.publish( 'example1', ['test','a','b','c'] );
pubsub.publish( 'example1', [{'color':'blue'},{'text':'hello'}] );
// Subscribers basically "subscribe" (or listen)
// And once they've been "notified" their callback functions are invoked
var testSubscription = pubsub.subscribe( 'example1', testSubscriber );
// Unsubscribe if you no longer wish to be notified
setTimeout(function(){
pubsub.unsubscribe( testSubscription );
}, 0);
pubsub.publish( 'example1', 'hello again! (this will fail)' );
</pre>
</p>
<p>A jsFiddle version of this example can be found at <a href="http://jsfiddle.net/LxPrq/">http://jsfiddle.net/LxPrq/</a></p>
</p>
<p><strong>Note:</strong>If you are interested in a pub/sub pattern implementation using jQuery, I recommend Ben Alman's <a href="https://gist.github.com/661855">GitHub Gist</a> for an example of how to achieve this.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="mediatorpatternjavascript">The Mediator Pattern</h2>
<p>
The dictionary refers to a Mediator as 'a neutral party who assists in negotiations and conflict resolution'.
</p>
<p>
In software engineering, a Mediator is a behavioural design pattern that allows us to expose a unified interface through which the different parts of a system may communicate. If it appears a system may have too many direct relationships between modules (colleagues), it may be time to have a central point of control that modules communicate through instead. The Mediator promotes loose coupling by ensuring that instead of modules referring to each other explicitly, their interaction is handled through this central point.
</p>
<p>
If you would prefer an analogy, consider a typical airport traffic control system. A tower (Mediator) handles what planes (modules) can take off and land because all communications are done from the planes to the control tower, rather than from plane-to-plane. A centralized controller is key to the success of this system and that's really the role a mediator plays in software design.
</p>
<p>
In real-world terms, a mediator encapsulates how disparate modules interact with each other by acting as an intermediary. At it's most basic, a mediator could be implemented as a central base for accessing functionality as follows:</p>
<pre class="brush: js">
// Our app namespace can act as a mediator
var app = app || {};
// Communicate through the mediator for Ajax requests
app.sendRequest = function ( options ) {
return $.ajax($.extend({}, options);
}
// When a request for a URL resolves, do something with the view
app.populateView = function( url, view ){
$.when(app.sendRequest({url: url, method: 'GET'})
.then(function(){
//populate the view
});
}
// Empty a view of any content it may contain
app.resetView = function( view ){
view.html('');
}
</pre>
<p>That said, in the JavaScript world it's become quite common for the Mediator to act as a messaging bus on top of the Observer-pattern. Rather than modules calling a Publish/Subscribe implementation, they'll use a Mediator with these capabilities built in instead. A possible implementation of this (based on work by Ryan Florence) could look as follows:</p>
<pre class="brush: js">
var mediator = (function(){
// Subscribe to an event, supply a callback to be executed
// when that event is broadcast
var subscribe = function(channel, fn){
if (!mediator.channels[channel]) mediator.channels[channel] = [];
mediator.channels[channel].push({ context: this, callback: fn });
return this;
},
// Publish/broadcast an event to the rest of the application
publish = function(channel){
if (!mediator.channels[channel]) return false;
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = mediator.channels[channel].length; i < l; i++) {
var subscription = mediator.channels[channel][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
channels: {},
publish: publish,
subscribe: subscribe,
installTo: function(obj){
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
</pre>
<p>Here are two sample uses of the implementation from above. It's effectively centralized Publish/Subscribe where a mediated implementation of the Observer pattern is used:</p>
<pre class="brush: js">
(function( m ){
function initialize(){
// Set a default value for 'person'
var person = "tim";
// Subscribe to an event called 'nameChange' with
// a callback function which will log the original
// person's name and (if everything works) the new
// name
m.subscribe('nameChange', function( arg ){
console.log( person ); // tim
person = arg;
console.log( person ); // david
});
}
function updateName(){
// Publish/Broadcast the 'nameChange' event with the new data
m.publish( 'nameChange', 'david' );
}
})( mediator );
</pre>
<h3>Advantages &amp; Disadvantages</h3>
<p>The benefits of the Mediator pattern are that it simplifies object interaction and can aid with decoupling those using it as a communication hub. In the above example, rather than using the Observer pattern to explicitly set many-to-many listeners and events, a Mediator allows you to broadcast events globally between subscribers and publishers. Broadcasted events can be handled by any number of modules at once and a mediator can used for a number of other purposes such as permissions management, given that it can control what messages can be subscribed to and which can be broadcast.</p>
<p>
Perhaps the biggest downside of using the Mediator pattern is that it can introduce a single point of failure. Placing a Mediator between modules can also cause a performance hit as they are always communicating indirectly.Because of the nature of loose coupling, it's difficult to establish how a system might react by only looking at the broadcasts. That said, it's useful to remind ourselves that decoupled systems have a number of other benefits - if our modules communicated with each other directly, changes to modules (e.g another module throwing an exception) could easily have a domino effect on the rest of your application. This problem is less of a concern with decoupled systems.</p>
<p>At the end of the day, tight coupling causes all kinds of headaches and this is just another alternative solution, but one which can work very well if implemented correctly.</p>
<h3>Mediator Vs. Observer</h3>
<p>
Developers often wonder what the differences are between the Mediator pattern and the Observer pattern. Admittedly, there is a bit of overlap, but let's refer back to the GoF for an explanation:</p>
<p>
<em>"In the Observer pattern, there is no single object that encapsulates a constraint. Instead, the Observer and the Subject must cooperate to maintain the constraint. Communication patterns are determined by the way observers and subjects are interconnected: a single subject usually has many observers, and sometimes the observer of one subject is a subject of another observer."</em></p>
<p>
The Mediator pattern centralizes rather than simply just distributing. It places the responsibility for maintaining a constraint squarely in the mediator.</p>
<h3>Mediator Vs. Facade</h3>
<p>We will be covering the Facade pattern shortly, but for reference purposes some developers may also wonder whether there are similarities between the Mediator and Facade patterns. They do both abstract the functionality of existing modules, but there are some subtle differences.</p>
<p>
The Mediator centralizes communication between modules where it's explicitly referenced by these modules. In a sense this is multidirectional. The Facade however just defines a simpler interface to a module or system but doesn't add any additional functionality. Other modules in the system aren't directly aware of the concept of a facade and could be considered unidirectional.
</p>
<p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</p>
<h2 id="prototypepatternjavascript">The Prototype Pattern</h2>
<p>The GoF refer to the prototype pattern as one which creates objects based on a template of an existing object through cloning.</p>
<p>We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects. The prototype object itself is effectively used as a blueprint for each object the constructor creates. If the prototype of the constructor function used contains a property called 'name' for example (as per the code sample lower down), then each object created by that same constructor will also have this same property.</p>
<p>Looking at the definitions for the prototype pattern in existing literature non-specific to JavaScript, you *may* find references to concepts outside the scope of the language such as classes. The reality is that prototypal inheritance avoids using classes altogether. There isn't a 'definition' object nor a core object in theory. We're simply creating copies of existing functional objects.</p>
<p>One of the benefits of using the prototype pattern is that we're working with the strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. With other design patterns, this isn't always the case. Not only is the pattern an easy way to implement inheritance, but it can also come with a performance boost as well: when defining a function in an object, they're all created by reference (so all child objects point to the same function) instead of creating their own individual copies. </p>
<p>For those interested, real prototypal inheritance, as defined in the ECMAScript 5 standard, requires the use of <code>Object.create</code> which has only become broadly native at the time of writing. <code>Object.create</code> creates an object which has a specified prototype and which optionally contains specified properties (i.e <code>Object.create(prototype, optionalDescriptorObjects)</code>). We can also see this being demonstrated in the example below:</p>
<p>&nbsp;</p>
<pre class="brush: js">
// No need for capitalization as it's not a constructor
var someCar = {
drive: function() {},
name: 'Mazda 3'
};
// Use Object.create to generate a new car
var anotherCar = Object.create( someCar );
anotherCar.name = 'Toyota Camry';
</pre></p>
<p>&nbsp;</p>
<p>
Object.create allows you to easily implement advanced concepts such as differential inheritance where objects are able to directly inherit from other objects. With Object.create you're also able to initialise object properties using the second supplied argument. For example:
</p><p>&nbsp;</p>
<p>
<pre class="brush: js">
var vehicle = {
getModel : function(){
console.log( 'The model of this vehicle is..' + this.model );
}
};
var car = Object.create( vehicle, {
'id' : {
value: MY_GLOBAL.nextId(),
enumerable: true // writable:false, configurable:false by default
},
'model':{
value: 'Ford',
enumerable: true
}
});
</pre>
</p>
<p>
Here the properties can be initialized on the second argument of Object.create using an object literal using the syntax similar to that used by the Object.defineProperties and Object.defineProperty methods. It allows you to set the property attributes such as enumerable, writable or configurable.</p>
<p>If you wish to implement the prototype pattern without directly using Object.create, you can simulate the pattern as per the above example as follows:</p>
<p>&nbsp;</p>
<p>
<pre class="brush: js">
var vehiclePrototype = {
init: function( carModel ) {
this.model = carModel;
},
getModel: function() {
console.log( 'The model of this vehicle is..' + this.model );
}
};
function vehicle( model ) {
function F() {};
F.prototype = vehiclePrototype;
var f = new F();
f.init( model );
return f;
}
var car = vehicle( 'Ford Escort' );
car.getModel();
</pre>
</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="commandpatternjavascript">The Command Pattern</h2>
<p>The command pattern aims to encapsulate method invocation, requests or operations into a single object and gives you the ability to both parameterize and pass method calls around that can be executed at your discretion. In addition, it enables you to decouple objects invoking the action from the objects which implement them, giving you a greater degree of overall flexibility in swapping out concrete 'classes'.</p>
<p>If you haven't come across concrete classes before, they are best explained in terms of class-based programming languages and are related to the idea of abstract classes. An abstract class defines an interface, but doesn't necessarily provide implementations for all of its member functions. It acts as a base class from which others are derived. A derived class which implements the missing functionality is called a concrete class (you may find these concepts familiar if you're read about the Decorator or Prototype patterns).</p>
<p>The main idea behind the command pattern is that it provides you a means to separate the responsibilities of issuing commands from anything executing commands, delegating this responsibility to different objects instead.</p>
<p>Implementation wise, simple command objects bind together both an action and the object wishing to invoke the action. They consistently include an execution operation (such as <code>run()</code> or <code>execute()</code>). All command objects with the same interface can easily be swapped as needed and this is considered one of the larger benefits of the pattern.</p>
<p>To demonstrate the command pattern we're going to create a simple car purchasing service.</p>
<p><pre class="brush: js">
$(function(){
var CarManager = {
// request information
requestInfo: function( model, id ){
return 'The information for ' + model +
' with ID ' + id + ' is foobar';
},
// purchase the car
buyVehicle: function( model, id ){
return 'You have successfully purchased Item '
+ id + ', a ' + model;
},
// arrange a viewing
arrangeViewing: function( model, id ){
return 'You have successfully booked a viewing of '
+ model + ' ( ' + id + ' ) ';
}
};
})();
</pre></p>
<p>Now taking a look at the above code, we could easily execute our manager commands by directly invoking the methods, however in some situations we don't expect to invoke the inner methods inside the object directly.</p>
<p>The reason for this is that we don't want to increase the dependencies amongst objects i.e if the core login behind the CarManager changes, all our methods that carry out the processing with the manager have to be modified in the mean time. This would effectively go against the OOP methodology of loosely coupling objects as much as possible which we want to avoid.</p>
<p>Let's now expand on our CarManager so that our application of the command pattern results in the following: accept any process requests from the CarManager object where the contents of the request include the model and car ID.</p>
<p>Here is what we would like to be able to achieve:</p>
<p><pre class="brush: js">
CarManager.execute({commandType: "buyVehicle", operand1: 'Ford Escort', operand2: '453543'});
</pre>
</p>
<p>
As per this structure we should now add a definition for the "CarManager.execute" method as follows:
</p>
<p><pre class="brush: js">
CarManager.execute = function( command ){
return CarManager[command.request](command.model,command.carID);
};
</pre></p>
<p>Our final sample calls would thus look as follows:</p>
<p><pre class="brush: js">
CarManager.execute({request: "arrangeViewing", model: 'Ferrari', carID: '145523'});
CarManager.execute({request: "requestInfo", model: 'Ford Mondeo', carID: '543434'});
CarManager.execute({request: "requestInfo", model: 'Ford Escort', carID: '543434'});
CarManager.execute({request: "buyVehicle", model: 'Ford Escort', carID: '543434'});
</pre></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="drypatternjavascript">The DRY Pattern </h2>
<p><strong>Disclaimer: </strong>DRY is essentially a way of thinking and many patterns aim to achieve a level of DRY-ness with their design. In this section we'll be covering what it means for code to be DRY but also covering the DRY design pattern based on these same concepts.</p>
<p>A challenge that developers writing large applications frequently have is writing similar code multiple times. Sometimes this occurs because your script or application may have multiple similar ways of performing something. Repetitive code writing generally reduces productivity and leaves you open to having to re-write code you&rsquo;ve already written similar times before, thus leaving you with less time to add in new functionality.</p>
<p>DRY (don&rsquo;t repeat yourself) was created to simplify this - it&rsquo;s based on the idea that each part of your code should ideally only have one representation of each piece of knowledge in it that applies to your system. The key concept to take away here is that if you have code that performs a specific task, you shouldn&rsquo;t write that code multiple times through your applications or scripts.</p>
<p>When DRY is applied successfully, the modification of any element in the system doesn&rsquo;t change other logically-unrelated elements. Elements in your code that are logically related change uniformly and are thus kept in sync. </p>
<p>As other patterns covered display aspects of DRY-ness with JavaScript, let's take a look at how to write DRY code using jQuery. Note that where jQuery is used, you can easily substitute selections using vanilla JavaScript because jQuery is just JavaScript at an abstracted level.</p>
<p><strong>Non-DRY</strong></p>
<p>
<pre class="brush: js">
// Let's store some defaults about a car for reference
var defaultSettings = {};
defaultSettings['carModel']  = 'Mercedes';
defaultSettings['carYear']    = 2010;
defaultSettings['carMiles']   = 5000;
defaultSettings['carTint']    = 'Metallic Blue';
// Let's do something with this data if a checkbox is clicked
$('.someCheckbox').click(function(){ 
      
 if ( this.checked ){ 
              
$('#input_carModel').val(activeSettings.carModel);
$('#input_carYear').val(activeSettings.carYear);
$('#input_carMiles').val(activeSettings.carMiles);
$('#input_carTint').val(activeSettings.carTint);
 } else { 
              
$('#input_carModel').val('');     
$('#input_carYear').val(''); 
$('#input_carMiles').val('');
$('#input_carTint').val('');
 }
});
</pre>
<br>
</p>
<p><strong>&nbsp;</strong></p>
<p><strong>DRY</strong></p>
<p>
<pre class="brush: js">
$('.someCheckbox').click(function(){        
    var checked = this.checked,
fields = ['carModel', 'carYear', 'carMiles', 'carTint'];
    /*
        What are we repeating?
        1. input_ precedes each field name
        2. accessing the same array for settings
        3. repeating value resets
 
        What can we do?
        1. programmatically generate the field names
        2. access array by key 
        3. merge this call using terse coding (ie. if checked, 
            set a value, otherwise don't)
  */  
$.each(fields, function(i,key){
$('#input_' + key).val(checked ? defaultSettings[key] : '');
});
});
</pre><br>
</p>
<p>&nbsp;</p>
<h2 id="facadepatternjavascript">The Facade Pattern</h2>
<p>When we put up a facade, we present an outward appearance to the world which may conceal a very different reality. This was the inspiration for the name behind the next pattern we're going to review - the facade pattern. The facade pattern provides a convenient higher-level interface to a larger body of code, hiding its true underlying complexity. Think of it as simplifying the API being presented to other developers, something which almost always improves usability.</p>
<p>
Facades are a structural pattern which can often be seen in JavaScript libraries like jQuery where, although an implementation may support methods with a wide range of behaviors, only a 'facade' or limited abstraction of these methods is presented to the public for use.</p>
<p>
This allows us to interact with the facade rather than the subsystem behind the scenes. Whenever you're using jQuery's <code>$(el).css()</code> or <code>$(el).animate()</code> methods, you're actually using a facade - the simpler public interface that avoids you having to manually call the many internal methods in jQuery core required to get some behaviour working.</p>
<p>
The facade pattern both simplifies the interface of a class and it also decouples the class from the code that utilizes it. This gives us the ability to indirectly interact with subsystems in a way that can sometimes be less prone to error than accessing the subsystem directly. A facade's advantages include ease of use and often a small size-footprint in implementing the pattern. </p>
<p>
Let’s take a look at the pattern in action. This is an unoptimized code example, but here we're utilizing a facade to simplify an interface for listening to events cross-browser. We do this by creating a common method that can be used in one’s code which does the task of checking for the existence of features so that it can provide a safe and cross-browser compatible solution.</p>
<pre class="brush: js">
var addMyEvent = function( el,ev,fn ){
if(el.addEventListener){
el.addEventListener( ev,fn, false );
}else if(el.attachEvent){
el.attachEvent( 'on'+ ev, fn );
} else{
el['on' + ev] = fn;
}
};
</pre>
<p>
In a similar manner, we're all familiar with jQuery's <code>$(document).ready(..)</code>. Internally, this is actually being powered by a method called <code>bindReady()</code>, which is doing this:</p>
<pre class="brush: js">
bindReady: function() {
...
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
...
</pre>
<p>
This is another example of a facade, where the rest of the world simply uses the limited interface exposed by <code>$(document).ready(..)</code> and the more complex implementation powering it is kept hidden from sight.</p>
<p>
Facades don't just have to be used on their own, however. They can also be integrated with other patterns such as the module pattern. As you can see below, our instance of the module patterns contains a number of methods which have been privately defined. A facade is then used to supply a much simpler API to accessing these methods:
</p>
<pre class="brush: js">
var module = (function() {
var _private = {
i:5,
get : function() {
console.log('current value:' + this.i);
},
set : function( val ) {
this.i = val;
},
run : function() {
console.log( 'running' );
},
jump: function(){
console.log( 'jumping' );
}
};
return {
facade : function( args ) {
_private.set(args.val);
_private.get();
if ( args.run ) {
_private.run();
}
}
}
}());
module.facade({run: true, val:10});
//outputs current value: 10, running
</pre>
<p>
In this example, calling <code>module.facade()</code> will actually trigger a set of private behaviour within the module, but again, the user isn't concerned with this. We've made it much easier for them to consume a feature without needing to worry about implementation-level details.
</p>
<p>&nbsp;</p>
<h2 id="factorypatternjavascript">The Factory Pattern</h2>
<p>Similar to other creational patterns, the Factory Pattern deals with the problem of creating objects (which we can think of as &lsquo;factory products&rsquo;) without the need to specify the exact class of object being created.&nbsp; </p>
<p>Specifically, the Factory Pattern suggests defining an interface for creating an object where you allow the subclasses to decide which class to instantiate. This pattern handles the problem by defining a completely separate method for the creation of objects and which sub-classes are able to override so they can specify the &lsquo;type&rsquo; of factory product that will be created.</p>
<p>This can come in quite useful, in particular if the creation process involved is quite complex. eg. if it strongly depends on the settings in configuration files.</p>
<p>You can often find factory methods in frameworks where the code for a library may need to create objects of particular types which may be subclassed by scripts using the frameworks.</p>
<p>In our example, let&rsquo;s take the code used in the original Constructor pattern example and see what this would look like were we to optimize it using the Factory Pattern:</p>
<p>&nbsp;</p>
<p>
<pre class="brush: js">
var Car = (function() {
   var Car = function ( model, year, miles ){
       this.model = model;
       this.year   = year;
       this.miles = miles;
   };
   return function ( model, year, miles ) {
       return new Car( model, year, miles );
   };
})();
var civic = Car( "Honda Civic", 2009, 20000 );
var mondeo = Car("Ford Mondeo", 2010, 5000 );
/*
These are also valid:
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
*/
</pre>
<p>&nbsp;</p>
<h3>When To Use This Pattern</h3>
<p>The Factory pattern can be especially useful when applied to the following situations:
<ul>
<li>When your object's setup requires a high level of complexity</li>
<li>When you need to generate different instances depending on the environment</li>
<li>When you're working with many small objects that share the same properties</li>
</ul>
</p>
<p>&nbsp;</p>
<h3>When Not To Use This Pattern</h3>
<p>It's generally a good practice to not use the factory pattern in every situation as it can easily add an unnecessarily additional aspect of complexity to your code. It can also make some tests more difficult to run.
</p>
<br />
<br />
<br />
<h2 id="mixinpatternjavascript">The Mixin Pattern</h2>
<p>In traditional object-oriented programming languages, <strong>mixins</strong> are classes which provide the functionality to be inherited by a subclass. Inheriting from mixins are a means of collecting functionality and classes may inherit functionality from multiple mixins through multiple inheritance.</p>
<p>In the following example, we have a Car defined without any methods. We also have a constructor called 'Mixin'. What we're going to do is augment the Car so it has access to the methods within the Mixin.This code demonstrates how with JavaScript you can augment a constructor to have a particular method without using the typical inheritance methods or duplicating code for each constructor function you have.</p>
<p>
<pre class="brush: js">
// Car
var Car = function( settings ){
this.model = settings.model || 'no model provided';
this.colour = settings.colour || 'no colour provided';
};
// Mixin
var Mixin = function(){};
Mixin.prototype = {
driveForward: function(){
console.log('drive forward');
},
driveBackward: function(){
console.log('drive backward');
}
};
// Augment existing 'class' with a method from another
function augment( receivingClass, givingClass ) {
// only provide certain methods
if ( arguments[2] ) {
for (var i=2, len=arguments.length; i&lt;len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
// provide all methods
else {
for ( var methodName in givingClass.prototype ) {
/* check to make sure the receiving class doesn't
have a method of the same name as the one currently
being processed */
if ( !receivingClass.prototype[methodName] ) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
// Augment the Car have the methods 'driveForward' and 'driveBackward'*/
augment( Car, Mixin,'driveForward','driveBackward' );
// Create a new Car
var vehicle = new Car({model:'Ford Escort', colour:'blue'});
// Test to make sure we now have access to the methods
vehicle.driveForward();
vehicle.driveBackward();
</pre>
</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2 id="decoratorpatternjavascript">The Decorator Pattern</h2>
<p>The Decorator pattern is an alternative to creating subclasses. This pattern can be used to wrap objects within another object of the same interface and allows you to both add behaviour to methods and also pass the method call to the original object (i.e the constructor of the decorator).</p>
<p>The decorator pattern is often used when you need to keep adding new functionality to overridden methods. This can be achieved by stacking multiple decorators on top of one another. </p>
<p>What is the main benefit of using a decorator pattern? Well, if we examine our first definition, we mentioned that decorators are an alternative to subclassing. When a script is being run, subclassing adds behaviour that affects all the instances of the original class, whilst decorating does not. It instead can add new behaviour for individual objects, which can be of benefit depending on the application in question. Let&rsquo;s take a look at some code that implements the decorator pattern:</p>
<p>
<pre class="brush: js">
// This is the 'class' we're going to decorate
function Macbook(){
      this.cost = function(){
      return 1000;
     };
}
function Memory( macbook ){
    this.cost = function(){
  return macbook.cost() + 75;
  };
}
function BlurayDrive( macbook ){
   this.cost = function(){
  return macbook.cost() + 300;
  };
}
function Insurance( macbook ){
   this.cost = function(){
  return macbook.cost() + 250;
  };
}
 
// Sample usage
var myMacbook = new Insurance(new BlurayDrive(new Memory(new Macbook())));
console.log( myMacbook.cost() );
</pre></p>
<p>&nbsp;</p>
<p>
Here's another decorator example where when we invoke performTask on the decorator object, it both performs some behaviour and invokes performTask on the underlying object.</p>
<p>&nbsp;</p>
<pre class="brush: js">
function ConcreteClass(){
this.performTask = function(){
this.preTask();
console.log('doing something');
this.postTask();
};
}
function AbstractDecorator( decorated ){
this.performTask = function()
{
decorated.performTask();
};
}
function ConcreteDecoratorClass( decorated ){
this.base = AbstractDecorator;
this.base(decorated);
this.preTask = function(){
console.log('pre-calling..');
};
this.postTask = function(){
console.log('post-calling..');
};
}
var concrete = new ConcreteClass();
var decorator1 = new ConcreteDecoratorClass(concrete);
var decorator2 = new ConcreteDecoratorClass(decorator1);
decorator2.performTask();
</pre>
</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1 id="detailedpatterns">Patterns In Greater Detail</h1>
<p>&nbsp;</p>
<p>As a beginner, you should hopefully now have a basic understanding of many of the commonly used design patterns in JavaScript (as well as some which are less frequently implemented). In this next section, we're going to explore a selection of the patterns we've already reviewed in greater detail.</p>
<p>&nbsp;</p>
<h1 id="detailedobserver">The Observer (Pub/Sub) pattern</h1>
<p>&nbsp;</p>
<p>
As we saw earlier in the book, the general idea behind the Observer pattern is the promotion of loose coupling. Rather than single objects calling on the methods of other objects directly, they instead subscribes to a specific task or activity of another object and are notified when it occurs. Observers are also called Subscribers and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.</o>
<p>
When objects are no longer interested in being notified by the subject they are registered with, they can unregister (or unsubscribe) themselves. The subject will then in turn remove them from the observer collection.</p>
<p>
It's often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time. The definition of the observer pattern provided in the GoF book, <em>Design Patterns: Elements of Reusable Object-Oriented Software</em>, is:</p>
<p>
'One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves.'
</p>
<p>
Basically, the pattern describes subjects and observers forming a publish-subscribe relationship. Unlimited numbers of objects may observe events in the subject by registering themselves. Once registered to particular events, the subject will notify all observers when the event has been fired.</p>
<h2>Advantages</h2>
<p>
Arguably, the largest benefit of using pub/sub is the ability to break down our applications into smaller, more loosely coupled modules, which can also improve general manageability.
</p>
<p>
Pub/sub is also a pattern that encourages us to think hard about the relationships between different parts of your application, identifying what layers need to observe or listen for behaviour and which need to push notifications regarding behaviour occurring to other parts of our apps.</p>
<p>
Whilst it may not always be the best solution to every problem, it remains one of the best tools for designing decoupled systems and should be considered an important tool in any JavaScript developer's utility belt.</p>
<h2>Disadvantages</h2>
<p>
Consequently, some of the issues with the pub/sub pattern actually stem from its main benefit. By decoupling publishers from subscribers, it can sometimes become difficult to obtain guarantees that particular parts of our applications are functioning as we may expect.</p>
<p>
For example, publishers may make an assumption that one or more subscribers are listening to them. Say that we're using such an assumption to log or output errors regarding some application process. If the subscriber performing the logging crashes (or for some reason fails to function), the publisher won't have a way of seeing this due to the decoupled nature of the system.</p>
<h2>Implementations</h2>
<p>
One of the benefits of design patterns is that once we understand the basics behind how a particular pattern works, being able to interpret an implementation of it becomes significantly more straightforward. Luckily, popular JavaScript libraries such as dojo and YUI already have utilities that can assist in easily implementing your own pub/sub system.</p>
<p>
For those wishing to use the pub/sub pattern with vanilla JavaScript (or another library) AmplifyJS includes a clean, library-agnostic implementation of pub/sub that can be used with any library or toolkit. ScriptJunkie also has a tutorial on how to get started with Amplify's pub/sub that was recently published. You can of course also write your own implementation from scratch or also check out either PubSubJS or OpenAjaxHub, both of which are also library-agnostic.</p>
<p>
jQuery developers have quite a few options for pub/sub (in addition to Amplify) and can opt to use one of the many well-developed implementations ranging from Peter Higgins's jQuery plugin to Ben Alman's (optimized) gist on GitHub. Links to just a few of these can be found below.
</p>
<ul>
<li>Ben Alman's Pub/Sub gist <a href="https://gist.github.com/661855">https://gist.github.com/661855</a> (recommended)</li>
<li>Rick Waldron's jQuery-core style take on the above <a href="https://gist.github.com/705311">https://gist.github.com/705311</a></li>
<li>Peter Higgins' plugin <a href="http://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js">http://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js</a>.</li>
<li>AppendTo's Pub/Sub in AmplifyJS <a href="http://amplifyjs.com">http://amplifyjs.com</a></li>
<li>Ben Truyman's gist <a href="https://gist.github.com/826794">https://gist.github.com/826794</a></li>
</ul>
<p>&nbsp;</p>
<h2>Tutorial</h2>
<p>
So that we are able to get an appreciation for how many of the vanilla JavaScript implementations of the Observer pattern might work, let's take a walk through of a trimmed down version of Morgan Roderick's PubSubJS, which I've put together below. This demonstrates the core concepts of subscribe, publish as well as the concept of unsubscribing.</p>
<p>
I've opted to base our examples on this code as it sticks closely to both the method signatures and approach of implementation I would expect to see in a JavaScript version of the original observer pattern.</p>
<h3>Sample Pub/Sub implementation</h3>
<pre class="brush: js">
var PubSub = {};
(function(p){
"use strict";
var topics = {},
lastUid = -1;
var publish = function( topic , data){
if ( !topics.hasOwnProperty( topic ) ){
return false;
}
var notify = function(){
var subscribers = topics[topic],
throwException = function(e){
return function(){
throw e;
};
};
for ( var i = 0, j = subscribers.length; i < j; i++ ){
try {
subscribers[i].func( topic, data );
} catch( e ){
setTimeout( throwException(e), 0);
}
}
};
setTimeout( notify , 0 );
return true;
};
/**
* Publishes the topic, passing the data to it's subscribers
* @topic (String): The topic to publish
* @data: The data to pass to subscribers
**/
p.publish = function( topic, data ){
return publish( topic, data, false );
};
/**
* Subscribes the passed function to the passed topic.
* Every returned token is unique and should be stored if you need to unsubscribe
* @topic (String): The topic to subscribe to
* @func (Function): The function to call when a new topic is published
**/
p.subscribe = function( topic, func ){
// topic is not registered yet
if ( !topics.hasOwnProperty( topic ) ){
topics[topic] = [];
}
var token = (++lastUid).toString();
topics[topic].push( { token : token, func : func } );
// return token for unsubscribing
return token;
};
/**
* Unsubscribes a specific subscriber from a specific topic using the unique token
* @token (String): The token of the function to unsubscribe
**/
p.unsubscribe = function( token ){
for ( var m in topics ){
if ( topics.hasOwnProperty( m ) ){
for ( var i = 0, j = topics[m].length; i < j; i++ ){
if ( topics[m][i].token === token ){
topics[m].splice( i, 1 );
return token;
}
}
}
}
return false;
};
});
</pre>
<h3>Example 1: Basic use of publishers and subscribers</h3>
<p>
This could then be easily used as follows:
</p>
<pre class="brush: js">
// a sample subscriber (or observer)
var testSubscriber = function( topics , data ){
console.log( topics + ": " + data );
};
// add the function to the list of subscribers to a particular topic
// maintain the token (subscription instance) to enable unsubscription later
var testSubscription = PubSub.subscribe( 'example1', testSubscriber );
// publish a topic or message asyncronously
PubSub.publish( 'example1', 'hello scriptjunkie!' );
PubSub.publish( 'example1', ['test','a','b','c'] );
PubSub.publish( 'example1', [{'color':'blue'},{'text':'hello'}] );
// unsubscribe from further topics
setTimeout(function(){
PubSub.unsubscribe( testSubscription );
}, 0);
// test that we've fully unsubscribed
PubSub.publish( 'example1', 'hello again!');
</pre>
<h3>Real-time stock market application</h3>
<p>Next, let's imagine we have a web application responsible for displaying real-time stock information.</p>
<p>
The application might have a grid for displaying the stock stats and a counter for displaying the last point of update, as well as an underlying data model. When the data model changes, the application will need to update the grid and counter. In this scenario, our subject is the data model and the observers are the grid and counter.</p>
<p>
When the observers receive notification that the model itself has changed, they can update themselves accordingly.
</p>
<h3>Example 2: UI notifications using pub/sub</h3>
<p>
In the following example, we limit our usage of pub/sub to that of a notification system. Our subscriber is listening to the topic 'dataUpdated' to find out when new stock information is available. It then triggers 'gridUpdate' which goes on to call hypothetical methods that pull in the latest cached data object and re-render our UI components.
</p>
<p>
Note: the Mediator pattern is occasionally used to provide a level of communication between UI components without requiring that they communicate with each other directly. For example, rather than tightly coupling our applications, we can have widgets/components publish a topic when something interesting happens. A mediator can then subscribe to that topic and call the relevant methods on other components.
</p>
<pre class="brush: js">
var grid = {
refreshData: function(){
console.log('retrieved latest data from data cache');
console.log('updated grid component');
},
updateCounter: function(){
console.log('data last updated at: ' + getCurrentTime());
}
};
//a very basic mediator
var gridUpdate = function(topics, data){
grid.refreshData();
grid.updateCounter();
}
var dataSubscription = PubSub.subscribe( 'dataUpdated', gridUpdate );
PubSub.publish( 'dataUpdated', 'new stock data available!' );
PubSub.publish( 'dataUpdated', 'new stock data available!' );
function getCurrentTime(){
var date = new Date(),
m = date.getMonth() + 1,
d = date.getDate(),
y = date.getFullYear(),
t = date.toLocaleTimeString().toLowerCase(),
return (m + '/' + d + '/' + y + ' ' + t);
}
</pre>
<p>Whilst there's nothing terribly wrong with this, there are more optimal ways that we can utilize pub/sub to our advantage.</p>
<h3>Example 3: Taking notifications further</h3>
<p>
Rather than just notifying our subscribers that new data is available, why not actually push the new data through to gridUpdate when we publish a new notification from a publisher. In this next example, our publisher will notify subscribers with the actual data that's been updated as well as a timestamp from the data-source of when the new data was added.
</p>
<p>
In addition to avoiding data having to be read from a cached store, this also avoids client-side calculation of the current time whenever a new data entry gets published.</p>
<pre class="brush: js">
var grid = {
addEntry: function(data){
if (data !== 'undefined') {
console.log('Entry:'
+ data.title
+ ' Changenet / %'
+ data.changenet
+ '/' + data.percentage + ' % added');
}
},
updateCounter: function(timestamp){
console.log('grid last updated at: ' + timestamp);
}
};
var gridUpdate = function(topics, data){
grid.addEntry(data);
grid.updateCounter(data.timestamp);
}
var gridSubscription = PubSub.subscribe( 'dataUpdated', gridUpdate );
PubSub.publish('dataUpdated', { title: "Microsoft shares", changenet: 4, percentage: 33, timestamp: '17:34:12' });
PubSub.publish('dataUpdated', { title: "Dell shares", changenet: 10, percentage: 20, timestamp: '17:35:16' });
</pre>
<h3>Example 4: Decoupling applications using Ben Alman's pub/sub implementation</h3>
<p>
In the following movie ratings example, we'll be using Ben Alman's jQuery implementation of pub/sub to demonstrate how we can decouple a user interface. Notice how submitting a rating only has the effect of publishing the fact that new user and rating data is available.
</p>
<p>
It's left up to the subscribers to those topics to then delegate what happens with that data. In our case we're pushing that new data into existing arrays and then rendering them using the jQuery.tmpl plugin.</p>
<strong>HTML/Templates</strong>
<pre class="brush: js">
&lt;script id=&quot;userTemplate&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
&lt;li&gt;${user}
&lt;/script&gt;
&lt;script id=&quot;ratingsTemplate&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
&lt;li&gt;&lt;strong&gt;${movie}&lt;/strong&gt; was rated ${rating}/5
&lt;/script&gt;
&lt;div id=&quot;container&quot;&gt;
&lt;div class=&quot;sampleForm&quot;&gt;
&lt;p&gt;
&lt;label for=&quot;twitter_handle&quot;&gt;Twitter handle:&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;twitter_handle&quot; /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;movie_seen&quot;&gt;Name a movie you&#39;ve seen this year:&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;movie_seen&quot; /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;movie_rating&quot;&gt;Rate the movie you saw:&lt;/label&gt;
&lt;select id=&quot;movie_rating&quot;&gt;
&lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
&lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
&lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
&lt;option value=&quot;4&quot;&gt;4&lt;/option&gt;
&lt;option value=&quot;5&quot;ected&gt;5&lt;/option&gt;
&lt;/select&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;button id=&quot;add&quot;&gt;Submit rating&lt;/button&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;summaryTable&quot;&gt;
&lt;div id=&quot;users&quot;&gt;&lt;h3&gt;Recent users&lt;/h3&gt;&lt;/div&gt;
&lt;div id=&quot;ratings&quot;&gt;&lt;h3&gt;Recent movies rated&lt;/h3&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<strong>JavaScript</strong>
<pre class="brush: js">
(function($) {
var movieList = [],
userList = [];
/* subscribers */
$.subscribe( "/new/user", function( e, userName ){
if(userName.length){
userList.push({user: userName});
$( "#userTemplate" ).tmpl( userList[userList.length - 1] ).appendTo( "#users" );
}
});
$.subscribe( "/new/rating", function( e, movieTitle, userRating ){
if(movieTitle.length){
movieList.push({ movie: movieTitle, rating: userRating});
$( "#ratingsTemplate" ).tmpl( movieList[movieList.length - 1] ).appendTo( "#ratings" );
}
});
$('#add').bind('click', function(){
var strUser = $("#twitter_handle").val(),
strMovie = $("#movie_seen").val(),
strRating = $("#movie_rating").val();
$.publish('/new/user', strUser );
$.publish('/new/rating', [ strMovie, strRating] );
});
})(jQuery);
</pre>
<h3>Example 5: Decoupling an Ajax-based jQuery application</h3>
<p>
In our final example, we're going to take a practical look at how decoupling our code using pub/sub early on in the development process can save us some potentially painful refactoring later on. This is something Rebecca Murphey touched on in her pub/sub screencast and is another reason why pub/sub is favoured by so many developers in the community.</p>
<p>
Quite often in Ajax-heavy applications, once we've received a response to a request we want to achieve more than just one unique action. One could simply add all of their post-request logic into a success callback, but there are drawbacks to this approach.</p>
<p>
Highly coupled applications sometimes increase the effort required to reuse functionality due to the increased inter-function/code dependency. What this means is that although keeping our post-request logic hardcoded in a callback might be fine if we're just trying to grab a result set once, it's not as appropriate when we want to make further Ajax-calls to the same data source (and different end-behaviour) without rewriting parts of the code multiple times. Rather than having to go back through each layer that calls the same data-source and generalizing them later on, we can use pub/sub from the start and save time.</p>
<p>
Using pub/sub, we can also easily separate application-wide notifications regarding different events down to whatever level of granularity you're comfortable with, something which can be less elegantly done using other patterns.</p>
<p>
Notice how in our sample below, one topic notification is made when a user indicates they want to make a search query and another is made when the request returns and actual data is available for consumption. It's left up to the subscribers to then decide how to use knowledge of these events (or the data returned). The benefits of this are that, if we wanted, we could have 10 different subscribers utilizing the data returned in different ways but as far as the Ajax-layer is concerned, it doesn't care. Its sole duty is to request and return data then pass it on to whoever wants to use it. This separation of concerns can make the overall design of your code a little cleaner.</p>
<strong>HTML/Templates</strong>:
<pre class="brush: js">
&lt;form id=&quot;flickrSearch&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;tag&quot; id=&quot;query&quot;/&gt;
&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;submit&quot;/&gt;
&lt;/form&gt;
&lt;div id=&quot;lastQuery&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;searchResults&quot;&gt;&lt;/div&gt;
&lt;script id=&quot;resultTemplate&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
{{each(i, items) items}}
&lt;li&gt;&lt;p&gt;&lt;img src=&quot;${items.media.m}&quot;/&gt;&lt;/p&gt;&lt;/li&gt;
{{/each}}
&lt;/script&gt;
</pre>
<strong>JAVASCRIPT</strong>:
<pre class="brush: js">
(function($) {
$('#flickrSearch').submit(function( e ){
e.preventDefault();
var tags = $(this).find('#query').val();
if(!tags){return;}
$.publish('/search/tags', [ $.trim(tags) ]);
});
$.subscribe('/search/tags', function(tags){
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{ tags: tags, tagmode: 'any', format: 'json'},
function(data){
if(!data.items.length){ return; }
$.publish('/search/resultSet', [ data ]);
});
});
$.subscribe('/search/tags', function(tags){
$('#searchResults').html('<p>Searched for:<strong>' + tags + '</strong></p>');
});
$.subscribe('/search/resultSet', function(results){
var holder = $('#searchResults');
holder.html();
$('#resultTemplate').tmpl(results).appendTo(holder);
});
});
</pre>
<p>
The Observer pattern is useful for decoupling a number of different scenarios in application design and if you haven't been using it, I recommend picking up one of the pre-written implementations mentioned today and just giving it a try out. It's one of the easier design patterns to get started with but also one of the most powerful.</p>
<p>&nbsp;</p>
<h1 id="detailmvcmvp">MVC And MVP</h1>
<p>In this section, we&#39;re going to review two very important architectural patterns - MVC (Model-View-Controller) and MVP (Model-View-Presenter). In the past both of these patterns have been heavily used for structuring desktop and server-side applications, but it's only been in recent years that come to being applied to JavaScript.</p>
<p>As the majority of JavaScript developers currently using these patterns opt to utilize libraries such as Backbone.js for implementing an MVC/MV*-like structure, we will compare how modern solutions such as it differ in their interpretation of MVC compared to classical takes on these patterns.</p>
<p>Let us first now cover the basics.</p>
<h2>MVC</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 coordinating both the models and views. The pattern was originally designed by <a href="http://en.wikipedia.org/wiki/Trygve_Reenskaug">Trygve Reenskaug</a> during his time working on Smalltalk-80 (1979) where it was initially called Model-View-Controller-Editor. MVC went on to be described in depth in <a href="http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612">&ldquo;Design Patterns: Elements of Reusable Object-Oriented Software&rdquo;</a> (The &quot;GoF&quot; book) in 1994, which played a role in popularizing its use.</p>
<h3>Smalltalk-80 MVC</h3>
<p>It&#39;s important to understand what the original MVC pattern was aiming to solve as it&#39;s mutated quite heavily since the days of it&#39;s origin. Back in the 70&#39;s, graphical user-interfaces were far and few between and a concept 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 modelled concepts in the real world (e.g a photo, a person) and the presentation objects which were rendered to the user&#39;s screen.</p>
<p>The Smalltalk-80 implementaion 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&#39;s MVC architecture:</p>
<ul>
<li>A Domain element was known as a Model and were ignorant of the user-interface (Views and Controllers)</li>
<li>Presentation was taken care of by the View and the Controller, but there wasn&#39;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&#39;s role in this pair was handling user input (such as key-presses and click events), doing something sensible with them.</li>
<li>The Observer pattern was relied upon for updating 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&#39;s architecture many decades ago. In Smalltalk-80&#39;s MVC, the View and Controller both observe the Model. As mentioned in the bullet point above, anytime the Model changes, the Views react. A simple example of this is an application backed by stock market data - in order for the application to be useful, any change to the data in our Models 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 some further historical information about Smalltalk-80&#39;s MVC, I recommend reading his work.</p>
<h2>MVC For JavaScript Developers</h2>
<p>We&#39;ve reviewed the 70&#39;s, but let us now return to the here and now. In modern times, the MVC pattern has been applied to a diverse range of programming languages including of most relevance to us: JavaScript. JavaScript now has a number of frameworks boasting support for MVC (or variations on it, which we refer to as the MV* family), allowing developers to easily add structure to their applications without great effort. You&#39;ve likely come across at least one of these such frameworks, but they include the likes of Backbone, Ember.js and JavaScriptMVC. Given the importance of avoiding &quot;spaghetti&quot; code, a term which describes code that is very difficult to read or maintain due to its lack of structure, it&#39;s imperative that the modern JavaScript developer understand what this pattern provides. This allows us to effectively appreciate what these frameworks enable us to do differently.</p>
<p>We know that MVC is composed of three core components:</p>
<h3>Models</h3>
<p>Models manage the data for an application. They are concerned with neither the user-interface nor presentation layers but instead represent unique forms of data that an application may require. When a model changes (e.g when it is updated), it will typically notify its observers (e.g views, a concept we will cover shortly) that a change has occurred so that they may react accordingly.</p>
<p>To understand models further, let us imagine we have a JavaScript photo gallery application. In a photo gallery, the concept of a photo would merit its own model as it represents a unique kind of domain-specific data. Such a model may contain related attributes such as a caption, image source and additional meta-data. A specific photo would be stored in an instance of a model and a model may also be reusable. Below we can see an example of a very simplistic model implemented using Backbone.</p>
<pre class="brush: js">var Photo = Backbone.Model.extend({
// Default attributes for the photo
defaults: {
src: &quot;placeholder.jpg&quot;,
caption: &quot;A default image&quot;,
viewed: false
},
// Ensure that each photo created has an `src`.
initialize: function() {
this.set({&quot;src&quot;: this.defaults.src});
}
});
</pre>
<p>The built-in capabilities of models vary across frameworks, however it is quite common for them to support validation of attributes, where attributes represent the properties of the model, such as a model identifier. When using models in real-world applications we generally also desire model persistence. Persistence allows us to edit and update models with the knowledge that its most recent state will be saved in either: memory, in a user&#39;s localStorage data-store or synchronized with a database.</p>
<p>In addition, a model may also have multiple views observing it. If say, our photo model contained meta-data such as its location (longitude and latitude), friends that were present in the a photo (a list of identifiers) and a list of tags, a developer may decide to provide a single view to display each of these three facets.</p>
<p>It is not uncommon for modern MVC/MV* frameworks to provide a means to group models together (e.g in Backbone, these groups are referred to as &quot;collections&quot;). Managing models in groups allows us to write application logic based on notifications from the group should any model it contains be changed. This avoids the need to manually observe individual model instances.</p>
<p>A sample grouping of models into a simplified Backbone collection can be seen below.</p>
<pre class="brush: js">var PhotoGallery = Backbone.Collection.extend({
// Reference to this collection&#39;s model.
model: Photo,
// Filter down the list of all photos
// that have been viewed
viewed: function() {
return this.filter(function( photo ){
return photo.get(&#39;viewed&#39;);
});
},
// Filter down the list to only photos that
// have not yet been viewed
unviewed: function() {
return this.without.apply( this, this.viewed() );
}
});
</pre>
<p>Should you read any of the older texts on MVC, you may come across a description of models as also managing application &#39;state&#39;. In JavaScript applications &quot;state&quot; has a different meaning, typically referring to the current &quot;state&quot; i.e view or sub-view (with specific data) on a users screen at a fixed point. State is a topic which is regularly discussed when looking at Single-page applications, where the concept of state needs to be simulated.</p>
<p>So to summarize, models are primarily concerned with business data.</p>
<h3>Views</h3>
<p>Views are a visual representation of models that present a filtered view of their current state. A view typically observes a model and is notified when the model changes, allowing the view to update itself accordingly. Design pattern literature commonly refers to views as &#39;dumb&#39; given that their knowledge of models and controllers in an application is limited.</p>
<p>Users are able to interact with views and this includes the ability to read and edit (i.e get or set the attribute values in) models. As the view is the presentation layer, we generally present the ability to edit and update in a user-friendly fashion. For example, in the former photo gallery application we discussed earlier, model editing could be facilitated through an &quot;edit&quot; view where a user who has selected a specific photo could edit its meta-data.</p>
<p>The actual task of updating the model falls to controllers (which we&#39;ll be covering shortly).</p>
<p>Let&#39;s explore views a little further using a vanilla JavaScript sample implementation. Below we can see a function that creates a single Photo view, consuming both a model instance and a controller instance.</p>
<p>We define a <code>render()</code> utility within our view which is responsible for rendering the contents of the <code>photoModel</code> using a JavaScript templating engine (Underscore templating) and updating the contents of our view, referenced by <code>photoEl</code>.</p>
<p>The <code>photoModel</code> then adds our <code>render()</code> callback as one of it&#39;s subscribers so that through the Observer pattern we can trigger the view to update when the model changes.</p>
<p>You may wonder where user-interaction comes into play here. When users click on any elements within the view, it&#39;s not the view&#39;s responsibility to know what to do next. It relies on a controller to make this decision for it. In our sample implementation, this is achieved by adding an event listener to <code>photoEl</code> which will delegate handling the click behaviour back to the controller, passing the model information along with it in case it&#39;s needed.</p>
<p>The benefit of this architecture is that each component plays it&#39;s own separate role in making the application function as needed.</p>
<pre class="brush: js">var buildPhotoView = function( photoModel, photoController ){
var base = document.createElement(&#39;div&#39;),
photoEl = document.createElement(&#39;div&#39;);
base.appendChild(photoEl);
var render= function(){
// We use a templating library such as Underscore
// templating which generates the HTML for our
// photo entry
photoEl.innerHTML = _.template(&#39;photoTemplate&#39;,
{src: photoModel.getSrc()});
}
photoModel.addSubscriber( render );
photoEl.addEventListener(&#39;click&#39;, function(){
photoController.handleEvent(&#39;click&#39;, photoModel );
});
var show = function(){
photoEl.style.display = &#39;&#39;;
}
var hide = function(){
photoEl.style.display = &#39;none&#39;;
}
return{
showView: show,
hideView: hide
}
}
</pre>
<p><strong>Templating</strong></p>
<p>In the context of JavaScript frameworks that support MVC/MV*, it is worth briefly discussing JavaScript templating and its relationship to views as we briefly touched upon it in the last section.</p>
<p>It has long been considered (and proven) a performance bad practice to manually create large blocks of HTML markup in-memory through string concatenation. Developers doing so have fallen prey to inperformantly iterating through their data, wrapping it in nested divs and using outdated techniques such as <code>document.write</code> to inject the &#39;template&#39; into the DOM. As this typically means keeping scripted markup inline with your standard markup, it can quickly become both difficult to read and more importantly, maintain such disasters, especially when building non-trivially sized applications.</p>
<p>JavaScript templating solutions (such as Handlebars.js and Mustache) are often used to define templates for views as markup (either stored externally or within script tags with a custom type - e.g text/template) containing template variables. Variables may be deliminated using a variable syntax (e.g {{name}}) and frameworks are typically smart enough to accept data in a JSON form (of which model instances can be converted to) such that we only need be concerned with maintaining clean models and clean templates. Most of the grunt work to do with population is taken care of by the framework itself. This has a large number of benefits, particularly when opting to store templates externally as this can give way to templates being dynamically loaded on an as-needed basis when it comes to building larger applications.</p>
<p>Below we can see two examples of HTML templates. One implemented using the popular Handlebars.js framework and another using Underscore&#39;s templates.</p>
<p><strong>Handlebars.js:</strong></p>
<pre class="brush: js">&lt;li class=&quot;photo&quot;&gt;
&lt;h2&gt;{{caption}}&lt;/h2&gt;
&lt;img class=&quot;source&quot; src=&quot;{{src}}&quot;/&gt;
&lt;div class=&quot;meta-data&quot;&gt;
{{metadata}}
&lt;/div&gt;
&lt;/li&gt;
</pre>
<p><strong>Underscore.js Microtemplates:</strong></p>
<pre class="brush: js">&lt;li class=&quot;photo&quot;&gt;
&lt;h2&gt;&lt;%= caption %&gt;&lt;/h2&gt;
&lt;img class=&quot;source&quot; src=&quot;&lt;%= src %&gt;&quot;/&gt;
&lt;div class=&quot;meta-data&quot;&gt;
&lt;%= metadata %&gt;
&lt;/div&gt;
&lt;/li&gt;
</pre>
<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 simply be dynamically rendered in a new view within the same page without any such refresh being necessary. The role of navigation thus falls to a &quot;router&quot;, which assists in managing application state (e.g allowing users to bookmark a particular view they have navigated to). As routers are however neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.</p>
<p>To summarize, views are a visual representation of our application data.</p>
<h3>Controllers</h3>
<p>Controllers are an intermediary between models and views which are classically responsible for two tasks: they both update the view when the model changes and update the model when the user manipulates the view.</p>
<p>In our photo gallery application, a controller would be responsible for handling changes the user made to the edit view for a particular photo, updating a specific photo model when a user has finished editing.</p>
<p>In terms of where most JavaScript MVC frameworks detract from what is conventionally considered &quot;MVC&quot; however, it is with controllers. The reasons for this vary, but in my honest opinion it is that framework authors initially look at the server-side interpretation of MVC, realize that it doesn&#39;t translate 1:1 on the client-side and re-interpret the C in MVC to mean something they feel makes more sense. The issue with this however is that it is subjective, increases the complexity in both understanding the classical MVC pattern and of course the role of controllers in modern frameworks.</p>
<p>As an example, let&#39;s briefly review the architecture of the popular architectural framework Backbone.js. Backbone contains models and views (somewhat similar to what we reviewed earlier), however it doesn&#39;t actually have true controllers. Its views and routers act a little similar to a controller, but neither are actually controllers on their own.</p>
<p>In this respect, contrary to what might be mentioned in the official documentation or in blog posts, Backbone is neither a truly MVC/MVP nor MVVM framework. It&#39;s in fact better to consider 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 advice from classical literature on the former to help with the latter.</p>
<h3>Controllers in another library (Spine.js) vs Backbone.js</h3>
<p><strong>Spine.js</strong></p>
<p>We now know that controllers are traditionally responsible for updating the view when the model changes (and similarly the model when the user updates the view). As the framework we&#39;ll be discussing in this book (Backbone) doesn&#39;t have it&#39;s <strong>own</strong> explicit controllers, it can be useful for us to review the controller from another MVC framework to appreciate the difference in implementations. For this, let&#39;s take a look at a sample controller from Spine.js:</p>
<p>In this example, we&#39;re going to have a controller called <code>`PhotosController</code> which will be in charge of individual photos in the application. It will ensure that when the view updates (e.g a user editd the photo meta-data) the corresonding model does too.</p>
<p>Note: We won&#39;t be delving heavily into Spine.js at all, but will just take a ten-foot view of what it&#39;s controllers can do:</p>
<pre class="brush: js">// Controllers in Spine are created by inheriting from Spine.Controller
var PhotosController = Spine.Controller.sub({
init: function(){
this.item.bind(&quot;update&quot;, this.proxy(this.render));
this.item.bind(&quot;destroy&quot;, this.proxy(this.remove));
},
render: function(){
// Handle templating
this.replace($(&quot;#photoTemplate&quot;).tmpl(this.item));
return this;
},
remove: function(){
this.el.remove();
this.release();
}
});
</pre>
<p>In Spine, controllers are considered the glue for an application, adding and responding to DOM events, rendering templates and ensuring that views and models are kept in sync (which makes sense in the context of what we know to be a controller).</p>
<p>What we&#39;re doing in the above example is setting up listeners in the <code>update</code> and <code>destroy</code> events using <code>render()</code> and <code>remove()</code>. When a photo entry gets updated , we re-render the view to reflect the changes to the meta-data. Similarly, if the photo gets deleted from the gallery, we remove it from the view. In case you were wondering about the <code>tmpl()</code> function in the code snippet: in the <code>render()</code> function, we&#39;re using this to render a JavaScript template called #photoTemplate which simply returns a HTML string used to replace the controller&#39;s current element.</p>
<p>What this provides us with is a very lightweight, simple way to manage changes between the model and the view.</p>
<p><strong>Backbone.js</strong></p>
<p>Later on in this section we&#39;re going to revisit the differences between Backbone and traditional MVC, but for now let&#39;s focus on controllers.</p>
<p>In Backbone, one shares the responsibility of a controller with both the Backbone.View and Backbone.Router. Some time ago Backbone did once come with it&#39;s own Backbone.Controller, but as the naming for this component didn&#39;t make sense for the context in which it was being used, it was later renamed to Router.</p>
<p>Routers handle a little more of the controller responsibility as it&#39;s possible to bind the events there for models and have your view respond to DOM events and rendering. As Tim Branyen (another Bocoup-based Backbone contributor) has also previously pointed out, it&#39;s possible to get away with not needing Backbone.Router at all for this, so a way to think about it using the Router paradigm is probably:</p>
<pre class="brush: js">var PhotoRouter = Backbone.Router.extend({
routes: { &quot;photos/:id&quot;: &quot;route&quot; },
route: function(id) {
var item = photoCollection.get(id);
var view = new PhotoView({ model: item });
something.html( view.render().el );
}
}):
</pre>
<p>To summarize, the takeaway from this section is that controllers manage the logic and coordination between models and views in an application.</p>
<h2>What does MVC give us?</h2>
<p>This separation of concerns in MVC facilitates simpler modularization of an application&#39;s functionality and enables:</p>
<ul>
<li>Easier overall maintenance. When updates need to be made to the application it is very 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 is significantly more straight-forward to write unit tests for business logic</li>
<li>Duplication of low-level model and controller code (i.e what you may have been using instead) 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>Delving deeper</h3>
<p>Right now, you likely have a basic understanding of what the MVC pattern provides, but for the curious, we can 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 &quot;set of classes to build a user interface&quot;. In their view, it&#39;s actually a variation of three other classical design patterns: the Observer (Pub/Sub), Strategy and Composite patterns. Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. </p>
<p>As we&#39;ve discussed, models represent application data whilst views are what the user is presented on screen. As such, MVC relies on Pub/Sub for some of its core communication (something that surprisingly isn&#39;t cover in many articles about the MVC pattern). When a model is changed it notifies the rest of the application it has been updated. The controller then updates the view accordingly. The observer 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 implement), one of the goal&#39;s of the pattern is to help define one-to-many relationships between a topic and its observers. When a topic changes, its observers are updated. Views and controllers have a slightly different relationship. Controllers facilitate views to respond to different user input and are an example of the Strategy pattern.</p>
<h3>Summary</h3>
<p>Having reviewed the classical MVC pattern, we should now understand how it allows us to cleanly separate concerns in an application. We should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of the MVC pattern, which although quite open to variation, still shares some of the fundamental concepts the original pattern has to offer.</p>
<p>When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and review how it&#39;s opted to approach architecture (specifically, how it supports implementing models, views, controllers or other alternatives) as this can better help you grok how the framework expects to be used.</p>
<h2>MVP</h2>
<p>Model-view-presenter (MVP) is a derivative of the MVC design pattern which focuses on improving presentation logic. It originated at a company named <a href="http://en.wikipedia.org/wiki/Taligent">Taligent</a> in the early 1990s while they were working on a model for a C++ CommonPoint environment. Whilst both MVC and MVP target the separation of concerns across multiple components, there are some fundamental differences between them.</p>
<p>For the purposes of this summary we will focus on the version of MVP most suitable for web-based architectures.</p>
<h3>Models, Views &amp; Presenters</h3>
<p>The P in MVP stands for presenter. It&#39;s a component which contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things such as being able to mock views in unit tests.</p>
<p>The most common implementation of MVP is one which uses a Passive View (a view which is for all intents and purposes &quot;dumb&quot;), containing little to no logic. MVP models are almost identical to MVC models and handle application data. The presenter acts as a mediator which talks to both the view and model, however both of these are isolated from each other. They effectively bind models to views, a responsibility which was previously held by controllers in MVC. Presenters are at the heart of the MVP pattern and as you can guess, incorporate the presentation logic behind views.</p>
<p>Solicited by a view, presenters perform any work to do with user requests and pass data back to them. In this respect, they retrieve data, manipulate it and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events but it&#39;s the presenters role to subscribe to them so that it can update the view. In this passive architecture, we have no concept of direct data binding. Views expose setters which presenters can use to set data.</p>
<p>The benefit of this change from MVC is that it increases the testability of your application and provides a more clean separation between the view and the model. This isn&#39;t however without its costs as the lack of data binding support in the pattern can often mean having to take care of this task separately.</p>
<p>Although a common implementation of a <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a> is for the view to implement an interface, there are variations on it, including the use of events which can decouple the View from the Presenter a little more. As we don&#39;t have the interface construct in JavaScript, we&#39;re using more a protocol than an explicit interface here. It&#39;s technically still an API and it&#39;s probably fair for us to refer to it as an interface from that perspective.</p>
<p>There is also a <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a> variation of MVP, which is closer to the MVC and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> patterns as it provides data-binding from the Model directly from the View. Key-value observing (KVO) plugins (such as Derick Bailey&#39;s Backbone.ModelBinding plugin) tend to bring Backbone out of the Passive View and more into the Supervising Controller or MVVM variations.</p>
<h2>MVP or MVC?</h2>
<p>MVP is generally used most often in enterprise-level applications where it&#39;s necessary to reuse as much presentation logic as possible. Applications with very complex views and a great deal of user interaction may find that MVC doesn&#39;t quite fit the bill here as solving this problem may mean heavily relying on multiple controllers. In MVP, all of this complex logic can be encapsulated in a presenter, which can simplify maintenance greatly.</p>
<p>As MVP views are defined through an interface and the interface is technically the only point of contact between the system and the view (other than a presenter), this pattern also allows developers to write presentation logic without needing to wait for designers to produce layouts and graphics for the application.</p>
<p>Depending on the implementation, MVP may be more easy to automatically unit test than MVC. The reason often cited for this is that the presenter can be used as a complete mock of the user-interface and so it can be unit tested independent of other components. In my experience this really depends on the languages you are implementing MVP in (there&#39;s quite a difference between opting for MVP for a JavaScript project over one for say, ASP.net).</p>
<p>At the end of the day, the underlying concerns you may have with MVC will likely hold true for MVP given that the differences between them are mainly semantic. As long as you are cleanly separating concerns into models, views and controllers (or presenters) you should be achieving most of the same benefits regardless of the pattern you opt for.</p>
<h2>MVC, MVP and Backbone.js</h2>
<p>There are very few, if any architectural JavaScript frameworks that claim to implement the MVC or MVC patterns in their classical form as many JavaScript developers don&#39;t view MVC and MVP as being mutually exclusive (we are actually more likely to see MVP strictly implemented when looking at web frameworks such as ASP.net or GWT). This is because it&#39;s possible to have additional presenter/view logic in your application and yet still consider it a flavor of MVC.</p>
<p>Backbone contributor <a href="http://ireneros.com/">Irene Ros</a> (of Boston-based Bocoup) subscribes to this way of thinking as when she separates views out into their own distinct components, she needs something to actually assemble them for her. This could either be a controller route (such as a <code>Backbone.Router</code>, covered later in the book) or a callback in response to data being fetched.</p>
<p>That said, some developers do however feel that Backbone.js better fits the description of MVP than it does MVC . Their view is that:</p>
<ul>
<li>The presenter in MVP better describes the <code>Backbone.View</code> (the layer between View templates and the data bound to it) than a controller does</li>
<li>The model fits <code>Backbone.Model</code> (it isn&#39;t greatly different to the models in MVC at all)</li>
<li>The views best represent templates (e.g Handlebars/Mustache markup templates)</li>
</ul>
<p>A response to this could be that the view can also just be a View (as per MVC) because Backbone is flexible enough to let it be used for multiple purposes. The V in MVC and the P in MVP can both be accomplished by <code>Backbone.View</code> because they&#39;re able to achieve two purposes: both rendering atomic components and assembling those components rendered by other views.</p>
<p>We&#39;ve also seen that in Backbone the responsibility of a controller is shared with both the Backbone.View and Backbone.Router and in the following example we can actually see that aspects of that are certainly true.</p>
<p>Our Backbone <code>PhotoView</code> uses the Observer pattern to &#39;subscribe&#39; to changes to a View&#39;s model in the line <code>this.model.bind(&#39;change&#39;,...)</code>. It also handles templating in the <code>render()</code> method, but unlike some other implementations, user interaction is also handled in the View (see <code>events</code>).</p>
<pre class="brush: js">var PhotoView = Backbone.View.extend({
//... is a list tag.
tagName: &quot;li&quot;,
// Pass the contents of the photo template through a templating
// function, cache it for a single photo
template: _.template($(&#39;#photo-template&#39;).html()),
// The DOM events specific to an item.
events: {
&quot;click img&quot; : &quot;toggleViewed&quot;
},
// The PhotoView listens for changes to
// its model, re-rendering. Since there&#39;s
// a one-to-one correspondence between a
// **Photo** and a **PhotoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
_.bindAll(this, &#39;render&#39;);
this.model.bind(&#39;change&#39;, this.render);
this.model.bind(&#39;destroy&#39;, this.remove);
},
// Re-render the photo entry
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
// Toggle the `&quot;viewed&quot;` state of the model.
toggleViewed: function() {
this.model.viewed();
}
});
</pre>
<p>Another (quite different) opinion is that Backbone more closely resembles <a href="http://martinfowler.com/eaaDev/uiArchs.html#ModelViewController">Smalltalk-80 MVC</a>, which we went through earlier.</p>
<p>As regular Backbone user Derick Bailey has <a href="http://lostechies.com/derickbailey/2011/12/23/backbone-js-is-not-an-mvc-framework/">previously</a> put it, it&#39;s ultimately best not to force Backbone to fit any specific design patterns. Design patterns should be considered flexible guides to how applications may be structured and in this respect, Backbone fits neither MVC nor MVP. Instead, it borrows some of the best concepts from multiple architectural patterns and creates a flexible framework that just works well.</p>
<p>It <em>is</em> however worth understanding where and why these concepts originated, so I hope that my explanations of MVC and MVP have been of help. Call it <strong>the Backbone way</strong>, MV* or whatever helps reference its flavor of application architecture. Most structural JavaScript frameworks will adopt their own take on classical patterns, either intentionally or by accident, but the important thing is that they help us develop applications which are organized, clean and can be easily maintained.</p>
<p>&nbsp;</p>
<h1 id="detaildecorator">Decorator Pattern</h1>
<p>In this section we're going to continue exploring the <strong>decorator</strong> - a structural designpattern that promotes code reuse and is a flexible alternative to subclassing. This pattern is also useful for modifying existing systems where you may wish to add additional features to objects without the need to change the underlying code that uses them.</p>
<p><!--more--></p>
<p>Traditionally, the decorator is defined as a design pattern that allows behaviour to be added to an existing object dynamically. The idea is that the decoration itself isn&#39;t essential to the base functionality of an object otherwise it would be baked into the &#39;superclass&#39; object itself.</p>
<h2>Subclassing</h2>
<p>For developers unfamiliar with subclassing, here is a beginner&#39;s primer on them before we dive further into decorators: subclassing is a term that refers to inheriting properties for a new object from a base or &#39;superclass&#39; object.</p>
<p>In traditional OOP, a class B is able to extend another class A. Here we consider A a superclass and B a subclass of A. As such, all instances of B inherit the methods from A. B is however still able to define it&#39;s own methods, including those that override methods originally defined by A.</p>
<p>Should B need to invoke a method in A that has been overriden, we refer to this as method chaining. Should B need to invoke the constructor A() (the superclass), we call this constructor chaining.</p>
<p>In order to demonstrate subclassing, we first need a base object that can have new instances of itself created. Let&#39;s model this around the concept of a person.</p>
<pre class="brush: js">var subclassExample = subclassExample || {};
subclassExample = {
Person: function( firstName , lastName ){
this.firstName = firstName;
this.lastName = lastName;
this.gender = &#39;male&#39;
}
}
</pre>
<p>Next, we&#39;ll want to specify a new class (object) that&#39;s a subclass of the existing Person object. Let&#39;s imagine we want to add distinct properties to distinguish a Person from a Superhero whilst inheriting the properties of the Person &#39;superclass&#39;. As superheroes share many common traits with normal people (eg. name, gender), this should hopefully illustrate how subclassing works adequately.</p>
<pre class="brush: js">
//a new instance of Person can then easily be created as follows:
var clark = new subclassExample.Person( &quot;Clark&quot; , &quot;Kent&quot; );
//Define a subclass constructor for for &#39;Superhero&#39;:
subclassExample.Superhero = function( firstName, lastName , powers ){
/*
Invoke the superclass constructor on the new object
then use .call() to invoke the constructor as a method of
the object to be initialized.
*/
subclassExample.Person.call(this, firstName, lastName);
//Finally, store their powers, a new array of traits not found in a normal &#39;Person&#39;
this.powers = powers;
}
subclassExample.Superhero.prototype = new subclassExample.Person;
var superman = new subclassExample.Superhero( &quot;Clark&quot; ,&quot;Kent&quot; , [&#39;flight&#39;,&#39;heat-vision&#39;] );
console.log(superman); /* includes superhero props as well as gender*/
</pre>
<p>The Superhero definition creates an object which descends from Person. Objects of this type have properties of the objects that are above it in the chain and if we had set default values in the Person object, Superhero is capable of overriding any inherited values with values specific to it&#39;s object.</p>
<p>So where do decorators come in?</p>
<h2>Decorators</h2>
<p>As we've previously covered, Decorators are used when it&#39;s necessary to delegate responsibilities to an object where it doesn&#39;t make sense to subclass it. A common reason for this is that the number of features required demand for a very large quantity of subclasses. Can you imagine having to define hundreds or thousands of subclasses for a project? It would likely become unmanagable fairly quickly.</p>
<p>To give you a visual example of where this is an issue, imagine needing to define new kinds of Superhero: SuperheroThatCanFly, SuperheroThatCanRunQuickly and SuperheroWithXRayVision.</p>
<p>Now, what if s superhero had more than one of these properties?. We&#39;d need to define a subclass called SuperheroThatCanFlyAndRunQuickly , SuperheroThatCanFlyRunQuicklyAndHasXRayVision etc - effectively, one for each possible combination. As you can see, this isn&#39;t very manageable when you factor in different abilities.</p>
<p>The decorator pattern isn&#39;t heavily tied to how objects are created but instead focuses on the problem of extending their functionality. Rather than just using inheritance, where we&#39;re used to extending objects linearly, we work with a single base object and progressively add decorator objects which provide the additional capabilities. The idea is that rather than subclassing, we add (decorate) properties or methods to a base object so its a little more streamlined.</p>
<p>The extension of objects is something already built into JavaScript and as we know, objects can be extended rather easily with properties being included at any point. With this in mind, a very very simplistic decorator may be implemented as follows:</p>
<h3>Example 1: Basic decoration of existing object constructors with new functionality</h3>
<pre class="brush: js">function vehicle( vehicleType ){
/*properties and defaults*/
this.vehicleType = vehicleType || &#39;car&#39;,
this.model = &#39;default&#39;,
this.license = &#39;00000-000&#39;
}
/*Test instance for a basic vehicle*/
var testInstance = new vehicle(&#39;car&#39;);
console.log(testInstance);
/*vehicle: car, model:default, license: 00000-000*/
/*Lets create a new instance of vehicle, to be decorated*/
var truck = new vehicle(&#39;truck&#39;);
/*New functionality we&#39;re decorating vehicle with*/
truck.setModel = function( modelName ){
this.model = modelName;
}
truck.setColor = function( color ){
this.color = color;
}
/*Test the value setters and value assignment works correctly*/
truck.setModel(&#39;CAT&#39;);
truck.setColor(&#39;blue&#39;);
console.log(truck);
/*vehicle:truck, model:CAT, color: blue*/
/*Demonstrate &#39;vehicle&#39; is still unaltered*/
var secondInstance = new vehicle(&#39;car&#39;);
console.log(secondInstance);
/*as before, vehicle: car, model:default, license: 00000-000*/
</pre>
<p>This type of simplistic implementation is something you&#39;re likely familiar with, but it doesn&#39;t really demonstrate some of the other strengths of the pattern. For this, we&#39;re first going to go through my variation of the Coffee example from an excellent book called Head First Design Patterns by Freeman, Sierra and Bates, which is modelled around a Macbook purchase.</p>
<p>We&#39;re then going to look at psuedo-classical decorators.</p>
<h3>Example 2: Simply decorate objects with multiple decorators</h3>
<pre class="brush: js">//What we&#39;re going to decorate
function MacBook() {
this.cost = function () { return 997; };
this.screenSize = function () { return 13.3; };
}
/*Decorator 1*/
function Memory( macbook ) {
var v = macbook.cost();
macbook.cost = function() {
return v + 75;
}
}
/*Decorator 2*/
function Engraving( macbook ){
var v = macbook.cost();
macbook.cost = function(){
return v + 200;
};
}
/*Decorator 3*/
function Insurance( macbook ){
var v = macbook.cost();
macbook.cost = function(){
return v + 250;
};
}
var mb = new MacBook();
Memory(mb);
Engraving(mb);
Insurance(mb);
console.log(mb.cost()); //1522
console.log(mb.screenSize()); //13.3
</pre>
<p>Here, the decorators are overrriding the superclass .cost() method to return the current price of the Macbook plus with the cost of the upgrade being specified. It&#39;s considered a decoration as the original Macbook object&#39;s constructor methods which are not overridden (eg. screenSize()) as well as any other properties which we may define as a part of the Macbook remain unchanged and in tact.</p>
<p>As you can probably tell, there isn&#39;t really a defined &#39;interface&#39; in the above example and duck typing is used to shift the responsibility of ensuring an object meets an interface when moving from the creator to the receiver.</p>
<h2>Pseudo-classical decorators</h2>
<p>We&#39;re now going to examine the variation of the decorator presented in &#39;Pro JavaScript Design Patterns&#39; (PJDP) by Dustin Diaz and Ross Harmes.</p>
<p>Unlike some of the examples from earlier, Diaz and Harmes stick more closely to how decorators are implemented in other programming languages (such as Java or C++) using the concept of an &#39;interface&#39;, which we&#39;ll define in more detail shortly.</p>
<p><strong>Note:</strong> This particular variation of the decorator pattern is provided for reference purposes. If you find it overly complex for your application&#39;s needs, I recommend sticking to one the simplier implementations covered earlier, but I would still read the section. If you haven&#39;t yet grasped how decorators are different from subclassing, it may help!.</p>
<h3>Interfaces</h3>
<p>PJDP describes the decorator as a pattern that is used to transparently wrap objects inside other objects of the same interface. An interface is a way of defining the methods an object *should* have, however, it doesn&#39;t actually directly specify how those methods should be implemented.</p>
<p>They can also indicate what parameters the methods take, but this is considered optional.</p>
<p>So, why would you use an interface in JavaScript? The idea is that they&#39;re self-documenting and promote reusability. In theory, interfaces also make code more stable by ensuring changes to them must also be made to the classes implementing them.</p>
<p>Below is an example of an implementation of Interfaces in JavaScript using duck-typing - an approach that helps determine whether an object is an instance of constructor/object based on the methods it implements.</p>
<pre class="brush: js">var TodoList = new Interface(&#39;Composite&#39;, [&#39;add&#39;, &#39;remove&#39;]);
var TodoItem = new Interface(&#39;TodoItem&#39;, [&#39;save&#39;]);
// TodoList class
var myTodoList = function(id, method, action) {
// implements TodoList, TodoItem
...
};
...
function addTodo( todoInstance ) {
Interface.ensureImplements(todoInstance, TodoList, TodoItem);
// This function will throw an error if a required method is not implemented,
// halting execution of the function.
//...
}
</pre>
<p>where Interface.ensureImplements provides strict checking. If you would like to explore interfaces further, I recommend looking at Chapter 2 of Pro JavaScript design patterns. For the Interface class used above, see <a href="https://gist.github.com/1057989">here</a>.</p>
<p>The biggest problem with interfaces is that, as there isn&#39;t built-in support for them in JavaScript, there&#39;s a danger of us attempting to emulate the functionality of another language, however, we&#39;re going to continue demonstrating their use just to give you a complete view of how the decorator is implemented by other developers.</p>
<h3>This variation of decorators and abstract decorators</h3>
<p>To demonstrate the structure of this version of the decorator pattern, we&#39;re going to imagine we have a superclass that models a macbook once again and a store that allows you to &#39;decorate&#39; your macbook with a number of enhancements for an additional fee.</p>
<p>Enhancements can include upgrades to 4GB or 8GB Ram, engraving, Parallels or a case. Now if we were to model this using an individual subclass for each combination of enhancement options, it might look something like this:</p>
<pre class="brush: js">var Macbook = function(){
//...
}
var MacbookWith4GBRam = function(){},
MacbookWith8GBRam = function(){},
MacbookWith4GBRamAndEngraving = function(){},
MacbookWith8GBRamAndEngraving = function(){},
MacbookWith8GBRamAndParallels = function(){},
MacbookWith4GBRamAndParallels = function(){},
MacbookWith8GBRamAndParallelsAndCase = function(){},
MacbookWith4GBRamAndParallelsAndCase = function(){},
MacbookWith8GBRamAndParallelsAndCaseAndInsurance = function(){},
MacbookWith4GBRamAndParallelsAndCaseAndInsurance = function(){};
</pre>
<p>and so on.</p>
<p>This would be an impractical solution as a new subclass would be required for every possible combination of enhancements that are available. As we&#39;d prefer to keep things simple without maintaining a large set of subclasses, let&#39;s look at how decorators may be used to solve this problem better.</p>
<p>Rather than requiring all of the combinations we saw earlier, we should simply have to create five new decorator classes. Methods that are called on these enhancement classes would be passed on to our Macbook class.</p>
<p>In our next example, decorators transparently wrap around their components and can interestingly be interchanged astray use the same interface.</p>
<p>Here&#39;s the interface we&#39;re going to define for the Macbook:</p>
<pre class="brush: js">var Macbook = new Interface(&#39;Macbook&#39;, [&#39;addEngraving&#39;, &#39;addParallels&#39;, &#39;add4GBRam&#39;, &#39;add8GBRam&#39;, &#39;addCase&#39;]);
A Macbook Pro might thus be represented as follows:
var MacbookPro = function(){
//implements Macbook
}
MacbookPro.prototype = {
addEngraving: function(){
},
addParallels: function(){
},
add4GBRam: function(){
},
add8GBRam:function(){
},
addCase: function(){
},
getPrice: function(){
return 900.00; //base price.
}
};
</pre>
<p>We&#39;re not going to worry about the actual implementation at this point as we&#39;ll shortly be passing on all method calls that are made on them.</p>
<p>To make it easier for us to add as many more options as needed later on, an abstract decorator class is defined with default methods required to implement the Macbook interface, which the rest of the options will subclass.</p>
<p>Abstract decorators ensure that we can decorate a base class independently with as many decorators as needed in different combinations (remember the example earlier?) without needing to derive a class for every possible combination.</p>
<pre class="brush: js">//Macbook decorator abstract decorator class
var MacbookDecorator = function( macbook ){
Interface.ensureImplements(macbook, Macbook);
this.macbook = macbook;
}
MacbookDecorator.prototype = {
addEngraving: function(){
return this.macbook.addEngraving();
},
addParallels: function(){
return this.macbook.addParallels();
},
add4GBRam: function(){
return this.macbook.add4GBRam();
},
add8GBRam:function(){
return this.macbook.add8GBRam();
},
addCase: function(){
return this.macbook.addCase();
},
getPrice: function(){
return this.macbook.getPrice();
}
};
</pre>
<p>What&#39;s happening in the above sample is that the Macbook decorator is taking an object to use as the component. It&#39;s using the Macbook interface we defined earlier and for each method is just calling the same method on the component. We can now create our option classes just by using the Macbook decorator - simply call the superclass constructor and any methods can be overriden as per necessary.</p>
<pre class="brush: js">var CaseDecorator = function( macbook ){
/*call the superclass&#39;s constructor next*/
this.superclass.constructor(macbook);
}
/*Let&#39;s now extend the superclass*/
extend( CaseDecorator, MacbookDecorator );
CaseDecorator.prototype.addCase = function(){
return this.macbook.addCase() + &quot; Adding case to macbook &quot;;
};
CaseDecorator.prototype.getPrice = function(){
return this.macbook.getPrice() + 45.00;
};
</pre>
<p>As you can see, most of this is relatively easy to implement. What we&#39;re doing is overriding the addCase() and getPrice() methods that need to be decorated and we&#39;re achieving this by first executing the component&#39;s method and then adding to it.</p>
<p>As there&#39;s been quite a lot of information presented in this section so far, let&#39;s try to bring it all together in a single example that will hopefully highlight what we&#39;ve learned.</p>
<pre class="brush: js">//Instantiation of the macbook
var myMacbookPro = new MacbookPro();
//This will return 900.00
console.log(myMacbookPro.getPrice());
//Decorate the macbook
myMacbookPro = new CaseDecorator( myMacbookPro ); /*note*/
//This will return 945.00
console.log(myMacbookPro.getPrice());
</pre>
<p>An important note from PJDP is that in the line denoted *note*, Harmes and Diaz claim that it&#39;s important not to create a separate variable to store the instance of your decorators, opting for the same variable instead. The downside to this is that we&#39;re unable to access the original macbook object in our example, however we technically shouldn&#39;t need to further.</p>
<p>As decorators are able to modify objects dynamically, they&#39;re a perfect pattern for changing existing systems. Occasionally, it&#39;s just simpler to create decorators around an object versus the trouble of maintaining individual subclasses. This makes maintaining applications of this type significantly more straight-forward.</p>
<h2>Implementing decorators with jQuery</h2>
<p>As with other patterns I&#39;&#39;ve covered, there are also examples of the decorator pattern that can be implemented with jQuery. jQuery.extend() allows you to extend (or merge) two or more objects (and their properties) together into a single object either at run-time or dynamically at a later point.</p>
<p>In this scenario, a target object can be decorated with new functionality without necessarily breaking or overriding existing methods in the source/superclass object (although this can be done).</p>
<p>In the following example, we define three objects: defaults, options and settings. The aim of the task is to decorate the &#39;defaults&#39; object with additional functionality found in &#39;options&#39;, which we&#39;ll make available through &#39;settings&#39;. We must:</p>
<p>(a) Leave &#39;defaults&#39; in an untouched state where we don&#39;t lose the ability to access the properties or functions found in it a later point (b) Gain the ability to use the decorated properties and functions found in &#39;options&#39;</p>
<pre class="brush: js">var decoratorApp = decoratorApp || {};
/* define the objects we&#39;re going to use*/
decoratorApp = {
defaults:{
validate: false,
limit: 5,
name: &quot;foo&quot;,
welcome: function(){
//console.log(&#39;welcome!&#39;);
}
},
options:{
validate: true,
name: &quot;bar&quot;,
helloWorld: function(){
//console.log(&#39;hello&#39;);
}
},
settings:{},
printObj: function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + &quot;: &quot;;
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return &quot;{ &quot; + arr.join(&quot;, &quot;) + &quot; }&quot;;
}
}
/* merge defaults and options, without modifying defaults */
decoratorApp.settings = $.extend({}, decoratorApp.defaults,decoratorApp.options);
/* what we&#39;ve done here is decorated defaults in a way that provides access to the properties and functionality it has to offer (as well as that of the decorator &#39;options&#39;). defaults itself is left unchanged*/
$(&#39;#log&#39;).append(&quot;&lt;div&gt;&lt;b&gt;settings -- &lt;/b&gt;&quot; + decoratorApp.printObj(decoratorApp.settings) + &quot;&lt;/div&gt;&lt;div&gt;&lt;b&gt;options -- &lt;/b&gt;&quot; + decoratorApp. printObj(decoratorApp.options) + &quot;&lt;/div&gt;&lt;div&gt;&lt;b&gt;defaults -- &lt;/b&gt;&quot; +decoratorApp.printObj(decoratorApp.defaults) + &quot;&lt;/div&gt;&quot; );
/*
settings -- { validate: true, limit: 5, name: bar, welcome: function (){ console.log(&#39;welcome!&#39;); }, helloWorld: function (){ console.log(&#39;hello!&#39;); } }
options -- { validate: true, name: bar, helloWorld: function (){ console.log(&#39;hello!&#39;); } }
defaults -- { validate: false, limit: 5, name: foo, welcome: function (){ console.log(&#39;welcome!&#39;); } }
*/
</pre>
<h2>Pros and cons of the pattern</h2>
<p>Developers enjoy using this pattern as it can be used transparently and is also fairly flexible - as we&#39;ve seen, objects can be wrapped or &#39;decorated&#39; with new behavior and then continue to be used without needing to worry about the base object being modified. In a broader context, this pattern also avoids us needing to rely on large numbers of subclasses to get the same benefits.</p>
<p>There are however drawbacks that you should be aware of when implementing the pattern. If poorly managed, it can significantly complicate your application&#39;s architecture as it introduces many small, but similar objects into your namespace. The concern here is that in addition to becoming hard to manage, other developers unfamiliar with the pattern may have a hard time grasping why it&#39;s being used.</p>
<p>Sufficient commenting or pattern research should assist with the latter, however as long as you keep a handle on how widespread you use the decorator in your application you should be fine on both counts.</p>
<p>&nbsp;</p>
<h1 id="detailnamespacing">Namespacing Patterns</h1>
<p>In this section, I&#39;ll be discussing both intermediate and advanced patterns for namespacing in JavaScript. We&#39;re going to begin with the latter, however if you&#39;re new to namespacing with the language and would like to learn more about some of the fundamentals, please feel free to skip to <!--more-->the section titled &#39;<a href="#beginners">namespacing fundamentals</a>&#39; to continue reading.</p>
<h2>What is namespacing?</h2>
<p>In many programming languages, namespacing is a technique employed to avoid <b>collisions</b> with other objects or variables in the global namespace. They&#39;re also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.</p>
<p>In JavaScript, namespacing at an enterprise level is critical as it&#39;s important to safeguard your code from breaking in the event of another script on the page using the <b>same</b> variable or method names as you are. With the number of <b>third-party</b> tags regularly injected into pages these days, this can be a common problem we all need to tackle at some point in our careers. As a well-behaved &#39;citizen&#39; of the global namespace, it&#39;s also imperative that you do your best to similarly not prevent other developer&#39;s scripts executing due to the same issues.</p>
<p>&nbsp;</p>
<p>Whilst JavaScript doesn&#39;t really have built-in support for namespaces like other languages, it does have objects and closures which can be used to achieve a similar effect.</p>
<h2>Advanced namespacing patterns</h2>
<p>In this section, I&#39;ll be exploring some advanced patterns and utility techniques that have helped me when working on larger projects requiring a re-think of how application namespacing is approached. I should state that I&#39;m not advocating any of these as *the* way to do things, but rather just ways that I&#39;ve found work in practice.</p>
<h3>Automating nested namespacing</h3>
<p>As you&#39;re probably aware, a nested namespace provides an organized hierarchy of structures in an application and an example of such a namespace could be the following: <i>application.utilities.drawing.canvas.2d</i>. In JavaScript the equivalent of this definition using the object literal pattern would be:</p>
<pre class="brush: js">var application = {
utilities:{
drawing:{
canvas:{
2d:{
/*...*/
}
}
}
}
};
</pre>
<p>Wow, that&#39;s ugly.</p>
<p>One of the obvious challenges with this pattern is that each additional depth you wish to create requires yet another object to be defined as a child of some parent in your top-level namespace. This can become particularly laborious when multiple depths are required as your application increases in complexity.</p>
<p>How can this problem be better solved? In <a href="http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752">JavaScript Patterns</a>, <a href="http://jspatterns.com">Stoyan Stefanov</a> presents a very-clever approach for automatically defining nested namespaces under an existing global variable using a convenience method that takes a single string argument for a nest, parses this and automatically populates your base namespace with the objects required.</p>
<p>The method he suggests using is the following, which I&#39;ve updated it to be a generic function for easier re-use with multiple namespaces:</p>
<pre class="brush: js">// top-level namespace being assigned an object literal
var myApp = myApp || {};
// a convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extend( ns, ns_string ) {
var parts = ns_string.split(&#39;.&#39;),
parent = ns,
pl, i;
if (parts[0] == &quot;myApp&quot;) {
parts = parts.slice(1);
}
pl = parts.length;
for (i = 0; i &lt; pl; i++) {
// create a property if it doesnt exist
if (typeof parent[parts[i]] == &#39;undefined&#39;) {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
}
// sample usage:
// extend myApp with a deeply nested namespace
var mod = extend(myApp, &#39;myApp.modules.module2&#39;);
// the correct object with nested depths is output
console.log(mod);
// minor test to check the instance of mod can also
// be used outside of the myApp namesapce as a clone
// that includes the extensions
console.log(mod == myApp.modules.module2); //true
// further demonstration of easier nested namespace
// assignment using extend
extend(myApp, &#39;moduleA.moduleB.moduleC.moduleD&#39;);
extend(myApp, &#39;longer.version.looks.like.this&#39;);
console.log(myApp);
</pre>
<p>Web inspector output:</p>
<p><img border="0" src="http://addyosmani.com/blog/wp-content/uploads/2011/09/ns1.png" width="520" /></p>
<p>Note how where one would previously have had to explicitly declare the various nests for their namespace as objects, this can now be easily achieved using a single, cleaner line of code. This works exceedingly well when defining purely namespaces alone, but can seem a little less flexible when you want to define both functions and properties at the same time as declaring your namespaces. Regardless, it is still incredibly powerful and I regularly use a similar approach in some of my projects.</p>
<h3>Dependency declaration pattern</h3>
<p>In this section we&#39;re going to take a look at a minor augmentation to the nested namespacing pattern you may be used to seeing in some applications. We all know that local references to objects can decrease overall lookup times, but let&#39;s apply this to namespacing to see how it might look in practice:</p>
<pre class="brush: js">// common approach to accessing nested namespaces
myApp.utilities.math.fibonacci(25);
myApp.utilities.math.sin(56);
myApp.utilities.drawing.plot(98,50,60);
// with local/cached references
Var utils = myApp.utilities,
maths = utils.math,
drawing = utils.drawing;
// easier to access the namespace
maths.fibonacci(25);
maths.sin(56);
drawing.plot(98, 50,60);
// note that the above is particularly performant when
// compared to hundreds or thousands of calls to nested
// namespaces vs. a local reference to the namespace
</pre>
<p>Working with a local variable here is almost always faster than working with a top-level global (eg.myApp). It&#39;s also both more convenient and more performant than accessing nested properties/sub-namespaces on every subsequent line and can improve readability in more complex applications.</p>
<p>Stoyan recommends declaring localized namespaces required by a function or module at the top of your function scope (using the single-variable pattern) and calls this a dependancy declaration pattern. One if the benefits this offers is a decrease in locating dependencies and resolving them, should you have an extendable architecture that dynamically loads modules into your namespace when required.</p>
<p>In my opinion this pattern works best when working at a modular level, localizing a namespace to be used by a group of methods. Localizing namespaces on a per-function level, especially where there is significant overlap between namespace dependencies would be something I would recommend avoiding where possible. Instead, define it further up and just have them all access the same reference.</p>
<h3>Deep object extension</h3>
<p>An alternative approach to automatic namespacing is deep object extension. Namespaces defined using object literal notation may be easily extended (or merged) with other objects (or namespaces) such that the properties and functions of both namespaces can be accessible under the same namespace post-merge.</p>
<p>This is something that&#39;s been made fairly easy to accomplish with modern JavaScript frameworks (eg. see jQuery&#39;s <a href="http://api.jquery.com/jQuery.extend/">$.extend</a>), however, if you&#39;re looking to extend object (namespaces) using vanilla JS, the following routine may be of assistance.</p>
<pre class="brush: js">// extend.js
// written by andrew dupont, optimized by addy osmani
function extend(destination, source) {
var toString = Object.prototype.toString,
objTest = toString.call({});
for (var property in source) {
if (source[property] &amp;&amp; objTest == toString.call(source[property])) {
destination[property] = destination[property] || {};
extend(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
console.group(&quot;objExtend namespacing tests&quot;);
// define a top-level namespace for usage
var myNS = myNS || {};
// 1. extend namespace with a &#39;utils&#39; object
extend(myNS, {
utils:{
}
});
console.log(&#39;test 1&#39;, myNS);
//myNS.utils now exists
// 2. extend with multiple depths (namespace.hello.world.wave)
extend(myNS, {
hello:{
world:{
wave:{
test: function(){
/*...*/
}
}
}
}
});
// test direct assignment works as expected
myNS.hello.test1 = &#39;this is a test&#39;;
myNS.hello.world.test2 = &#39;this is another test&#39;;
console.log(&#39;test 2&#39;, myNS);
// 3. what if myNS already contains the namespace being added
// (eg. &#39;library&#39;)? we want to ensure no namespaces are being
// overwritten during extension
myNS.library = {
foo:function(){}
};
extend(myNS, {
library:{
bar:function(){
/*...*/
}
}
});
// confirmed that extend is operating safely (as expected)
// myNS now also contains library.foo, library.bar
console.log(&#39;test 3&#39;, myNS);
// 4. what if we wanted easier access to a specific namespace without having
// to type the whole namespace out each time?.
var shorterAccess1 = myNS.hello.world;
shorterAccess1.test3 = &quot;hello again&quot;;
console.log(&#39;test 4&#39;, myNS);
//success, myApp.hello.world.test3 is now &#39;hello again&#39;
console.groupEnd();
</pre>
<p>If you do happen to be using jQuery in your application, you can achieve the exact same object namespact extensibility using $.extend as seen below:</p>
<pre class="brush: js">// top-level namespace
var myApp = myApp || {};
// directly assign a nested namespace
myApp.library = {
foo:function(){ /*..*/}
};
// deep extend/merge this namespace with another
// to make things interesting, let&#39;s say it&#39;s a namespace
// with the same name but with a different function
// signature: $.extend(deep, target, object1, object2)
$.extend(true, myApp, {
library:{
bar:function(){
/*..*/
}
}
});
console.log(&#39;test&#39;, myApp);
// myApp now contains both library.foo() and library.bar() methods
// nothing has been overwritten which is what we&#39;re hoping for.
</pre>
<p>For the sake of thoroughness, please see <a href="https://gist.github.com/1221980">here</a> for jQuery $.extend equivalents to the rest of the namespacing experiments found in this section.</p>
<p><a name="beginners"></a></p>
<h2>Namespacing Fundamentals</h2>
<p>Namespaces can be found in almost any serious JavaScript application. Unless you&#39;re working with a code-snippet, it&#39;s imperative that you do your best to ensure that you&#39;re implementing namespacing correctly as it&#39;s not just simple to pick-up, it&#39;ll also avoid third party code clobbering your own. The patterns we&#39;ll be examining in this section are:</p>
<ol>
<li>Single global variables</li>
<li>Object literal notation</li>
<li>Nested namespacing</li>
<li>Immediately-invoked Function Expressions</li>
<li>Namespace injection</li>
</ol>
<h3>1.Single global variables</h3>
<p>One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:</p>
<pre class="brush: js">var myApplication = (function(){
function(){
/*...*/
},
return{
/*...*/
}
})();
</pre>
<p>Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.</p>
<p>One solution to this problem, as mentioned by <a href="http://michaux.ca/articles/javascript-namespacing">Peter Michaux</a>, is to use prefix namespacing. It&#39;s a simple concept at heart, but the idea is you select a unique prefix namespace you wish to use (in this example, &quot;myApplication_&quot;) and then define any methods, variables or other objects after the prefix as follows:</p>
<pre class="brush: js">var myApplication_propertyA = {};
var myApplication_propertyB = {};
funcion myApplication_myMethod(){ /*..*/ }
</pre>
<p>This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow. There is also quite a heavy reliance on your prefix not being used by any other developers in the global namespace, so be careful if opting to use this.</p>
<p>For more on Peter&#39;s views about the single global variable pattern, read his excellent post on them <a href="http://michaux.ca/articles/javascript-namespacing">here</a>.</p>
<h3>2. Object literal notation</h3>
<p>Object literal notation can be thought of as an object containing a collection of key:value pairs with a colon separating each pair of keys and values. It&#39;s syntax requires a comma to be used after each key:value pair with the exception of the last item in your object, similar to a normal array.</p>
<pre class="brush: js">var myApplication = {
getInfo:function(){ /**/ },
// we can also populate our object literal to support
// further object literal namespaces containing anything
// really:
models : {},
views : {
pages : {}
},
collections : {}
};
</pre>
<p>One can also opt for adding properties directly to the namespace:</p>
<pre class="brush: js">myApplication.foo = function(){
return &quot;bar&quot;;
}
myApplication.utils = {
toString:function(){
/*..*/
},
export: function(){
/*..*/
}
}
</pre>
<p>Object literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They&#39;re beneficial if you wish to create easily-readable structures that can be expanded to support deep nesting. Unlike simple global variables, object literals often also take into account tests for the existence of a variable by the same name so the chances of collision occurring are significantly reduced.</p>
<p>The code at the very top of the next sample demonstrates the different ways in which you can check to see if a variable (object namespace) already exists before defining it. You&#39;ll commonly see developers using Option 1, however Options 3 and 5 may be considered more thorough and Option 4 is considered a good best-practice.</p>
<pre class="brush: js">// This doesn&#39;t check for existence of &#39;myApplication&#39; in
// the global namespace. Bad practice as you can easily
// clobber an existing variable/namespace with the same name
var myApplication = {};
/*
The following options *do* check for variable/namespace existence.
If already defined, we use that instance, otherwise we assign a new
object literal to myApplication.
Option 1: var myApplication = myApplication || {};
Option 2 if(!MyApplication) MyApplication = {};
Option 3: var myApplication = myApplication = myApplication || {}
Option 4: myApplication || (myApplication = {});
Option 5: var myApplication = myApplication === undefined ? {} : myApplication;
*/
</pre>
<p>There is of course a huge amount of variance in how and where object literals are used for organizing and structuring code. For smaller applications wishing to expose a nested API for a particular self-enclosed module, you may just find yourself using this next pattern when returning an interface for other developers to use. It&#39;s a variation on the module pattern where the core structure of the pattern is an IIFE, however the returned interface is an object literal:</p>
<pre class="brush: js">var namespace = (function () {
// defined within the local scope
var privateMethod1 = function () { /* ... */ }
var privateMethod2 = function () { /* ... */ }
var privateProperty1 = &#39;foobar&#39;;
return {
// the object literal returned here can have as many
// nested depths as you wish, however as mentioned,
// this way of doing things works best for smaller,
// limited-scope applications in my personal opinion
publicMethod1: privateMethod1,
//nested namespace with public properties
properties:{
publicProperty1: privateProperty1
},
//another tested namespace
utils:{
publicMethod2: privateMethod2
}
...
}
})();
</pre>
<p>The benefit of object literals is that they offer us a very elegant key/value syntax to work with; one where we&#39;re able to easily encapsulate any distinct logic or functionality for our application in a way that clearly separates it from others and provides a solid foundation for extending your code.</p>
<p>A possible downside however is that object literals have the potential to grow into long syntactic constructs. Opting to take advantage of the nested namespace pattern (which also uses the same pattern as it&#39;s base)</p>
<p>This pattern has a number of other useful applications too. In addition to namespacing, it&#39;s often of benefit to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter them - object literals work great for this purpose. Here&#39;s an example of a hypothetical object literal for configuration:</p>
<pre class="brush: js">var myConfig = {
language: &#39;english&#39;,
defaults: {
enableGeolocation: true,
enableSharing: false,
maxPhotos: 20
},
theme: {
skin: &#39;a&#39;,
toolbars: {
index: &#39;ui-navigation-toolbar&#39;,
pages: &#39;ui-custom-toolbar&#39;
}
}
}
</pre>
<p>Note that there are really only minor syntactical differences between the object literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g. for simpler storage when sending to the back-end), feel free to. For more on the object literal pattern, I recommend reading Rebecca Murphey&#39;s excellent <a href="http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/">article</a> on the topic.</p>
<h3>3. Nested namespacing</h3>
<p>An extension of the object literal pattern is nested namespacing. It&#39;s another common pattern used that offers a lower risk of collision due to the fact that even if a namespace already exists, it&#39;s unlikely the same nested children do.</p>
<p>Does this look familiar?</p>
<p>&nbsp;</p>
<pre class="brush: js">YAHOO.util.Dom.getElementsByClassName(&#39;test&#39;);
</pre>
<p>&nbsp;</p>
<p>Yahoo&#39;s YUI framework uses the nested object namespacing pattern regularly and at AOL we also use this pattern in many of our main applications. A sample implementation of nested namespacing may look like this:</p>
<pre class="brush: js">var myApp = myApp || {};
// perform a similar existence check when defining nested
// children
myApp.routers = myApp.routers || {};
myApp.model = myApp.model || {};
myApp.model.special = myApp.model.special || {};
// nested namespaces can be as complex as required:
// myApp.utilities.charting.html5.plotGraph(/*..*/);
// myApp.modules.financePlanner.getSummary();
// myApp.services.social.facebook.realtimeStream.getLatest();
</pre>
<p>You can also opt to declare new nested namespaces/properties as indexed properties as follows:</p>
<pre class="brush: js">myApp[&quot;routers&quot;] = myApp[&quot;routers&quot;] || {};
myApp[&quot;models&quot;] = myApp[&quot;models&quot;] || {};
myApp[&quot;controllers&quot;] = myApp[&quot;controllers&quot;] || {};
</pre>
<p>Both options are readable, organized and offer a relatively safe way of namespacing your application in a similar fashion to what you may be used to in other languages. The only real caveat however is that it requires your browser&#39;s JavaScript engine first locating the myApp object and then digging down until it gets to the function you actually wish to use.</p>
<p>This can mean an increased amount of work to perform lookups, however developers such as <a href="http://twitter.com/kangax">Juriy Zaytsev</a> have previously tested and found the performance differences between single object namespacing vs the &#39;nested&#39; approach to be quite negligible.</p>
<h3>4. Immediately-invoked Function Expressions (IIFE)s</h3>
<p>An <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a> is effectively an unnamed function which is immediately invoked after it&#39;s been defined. In JavaScript, because both variables and functions explicitly defined within such a context may only be accessed inside of it, function invocation provides an easy means to achieving privacy.</p>
<p>This is one of the many reasons why IIFEs are a popular approach to encapsulating application logic to protect it from the global namespace. You&#39;ve probably come across this pattern before under the name of a self-executing (or self-invoked) anonymous function, however I personally prefer Ben Alman&#39;s naming convection for this particular pattern as I believe it to be both more descriptive and more accurate.</p>
<p>The simplest version of an IIFE could be the following:</p>
<pre class="brush: js">// an (anonymous) immediately-invoked function expression
(function(){ /*...*/})();
// a named immediately-invoked function expression
(function foobar(){ /*..*/}());
// this is technically a self-executing function which is quite different
function foobar(){ foobar(); }
</pre>
<p>whilst a slightly more expanded version of the first example might look like:</p>
<pre class="brush: js">var namespace = namespace || {};
// here a namespace object is passed as a function
// parameter, where we assign public methods and
// properties to it
(function( o ){
o.foo = &quot;foo&quot;;
o.bar = function(){
return &quot;bar&quot;;
};
})(namespace);
console.log(namespace);
</pre>
<p>Whilst readable, this example could be significantly expanded on to address common development concerns such as defined levels of privacy (public/private functions and variables) as well as convenient namespace extension. Let&#39;s go through some more code:</p>
<pre class="brush: js">// namespace (our namespace name) and undefined are passed here
// to ensure 1. namespace can be modified locally and isn&#39;t
// overwritten outside of our function context
// 2. the value of undefined is guaranteed as being truly
// undefined. This is to avoid issues with undefined being
// mutable pre-ES5.
;(function ( namespace, undefined ) {
// private properties
var foo = &quot;foo&quot;,
bar = &quot;bar&quot;;
// public methods and properties
namespace.foobar = &quot;foobar&quot;;
namespace.sayHello = function () {
speak(&quot;hello world&quot;);
};
// private method
function speak(msg) {
console.log(&quot;You said: &quot; + msg);
};
// check to evaluate whether &#39;namespace&#39; exists in the
// global namespace - if not, assign window.namespace an
// object literal
}(window.namespace = window.namespace || {});
// we can then test our properties and methods as follows
// public
console.log(namespace.foobar); // foobar
namescpace.sayHello(); // hello world
// assigning new properties
namespace.foobar2 = &quot;foobar&quot;;
console.log(namespace.foobar2);
</pre>
<p>Extensibility is of course key to any scalable namespacing pattern and IIFEs can be used to achieve this quite easily. In the below example, our &#39;namespace&#39; is once again passed as an argument to our anonymous function and is then extended (or decorated) with further functionality:</p>
<pre class="brush: js">// let&#39;s extend the namespace with new functionality
(function( namespace, undefined ){
// public method
namespace.sayGoodbye = function(){
console.log(namespace.foo);
console.log(namespace.bar);
speak(&#39;goodbye&#39;);
}
}( window.namespace = window.namespace || {});
</pre>
<p>namespace.sayGoodbye(); //goodbye</p>
<p>That&#39;s it for IIFEs for the time-being. If you would like to find out more about this pattern, I recommend reading both Ben&#39;s <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE post</a> and Elijah Manor&#39;s post on <a href="enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/">namespace patterns from C#</a>.</p>
<h3>5. Namespace injection</h3>
<p>Namespace injection is another variation on the IIFE where we &#39;inject&#39; the methods and properties for a specific namespace from within a function wrapper using <i>this</i> as a namespace proxy. The benefit this pattern offers is easy application of functional behaviour to multiple objects or namespaces and can come in useful when applying a set of base methods to be built on later (eg. getters and setters).</p>
<p>The disadvantages of this pattern are that there may be easier or more optimal approaches to achieving this goal (eg. deep object extension / merging) which I cover earlier in the article..</p>
<p>Below we can see an example of this pattern in action, where we use it to populate the behaviour for two namespaces: one initially defined (utils) and another which we dynamically create as a part of the functionality assignment for utils (a new namespace called <i>tools</i>).</p>
<pre class="brush: js">var myApp = myApp || {};
myApp.utils = {};
(function() {
var val = 5;
this.getValue = function() {
return val;
};
this.setValue = function(newVal) {
val = newVal;
}
// also introduce a new sub-namespace
this.tools = {};
}).apply(myApp.utils);
// inject new behaviour into the tools namespace
// which we defined via the utilities module
(function(){
this.diagnose = function(){
return &#39;diagnosis&#39;;
}
}).apply(myApp.utils.tools);
// note, this same approach to extension could be applied
// to a regular IIFE, by just passing in the context as
// an argument and modifying the context rather than just
// &#39;this&#39;
// testing
console.log(myApp); //the now populated namespace
console.log(myApp.utils.getValue()); // test get
myApp.utils.setValue(25); // test set
console.log(myApp.utils.getValue());
console.log(myApp.utils.tools.diagnose());
</pre>
<p>Angus Croll has also <a href="http://msdn.microsoft.com/en-us/scriptjunkie/gg578608">previously</a> suggested the idea of using the call API to provide a natural separation between contexts and arguments. This pattern can feel a lot more like a module creator, but as modules still offer an encapsulation solution, I&#39;ll briefly cover it for the sake of thoroghness:</p>
<pre class="brush: js">// define a namespace we can use later
var ns = ns || {}, ns2 = ns2 || {};
// the module/namespace creator
var creator = function(val){
var val = val || 0;
this.next = function(){
return val++
};
this.reset = function(){
val = 0;
}
}
creator.call(ns);
// ns.next, ns.reset now exist
creator.call(ns2, 5000);
// ns2 contains the same methods
// but has an overridden value for val
// of 5000
</pre>
<p>As mentioned, this type of pattern is useful for assigning a similar base set of functionality to multiple modules or namespaces, but I&#39;d really only suggest using it where explicitly declaring your functionality within an object/closure for direct access doesn&#39;t make sense.</p>
<p>Reviewing the namespace patterns above, the option that I would personally use for most larger applications is nested object namespacing with the object literal pattern.</p>
<p>IIFEs and single global variables may work fine for applications in the small to medium range, however, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that promotes readability and scales. I feel this pattern achieves all of these objectives well.</p>
<p>I would also recommend trying out some of the suggested advanced utility methods for namespace extension as they really can save you time in the long-run.</p>
<p>&nbsp;</p>
<h1 id="detailflyweight">Flyweight</h1>
<p>&nbsp;</p>
<p>The Flyweight pattern is considered a useful classical solution for code that's repetitive, slow and inefficient - for example: situations where we might create a large number of similar objects.</p>
<p>
It's of particular use in JavaScript where code that's complex in nature may easily use all of the available memory, causing a number of performance issues. Interestingly, it's been quite underused in recent years. Given how reliant we are on JavaScript for the applications of today, both performance and scalability are often paramount and this pattern (when applied correctly) can assist with improving both.</p>
<p>
To give you some quick historical context, the pattern is named after the boxing weight class that includes fighters weighing less than 112lb - Poncho Villa being the most famous fighter in this division. It derives from this weight classification as it refers to the small amount of weight (memory) used.</p>
<p>
Flyweights are an approach to taking several similar objects and placing that shared information into a single external object or structure. The general idea is that (in theory) this reduces the resources required to run an overall application. The flyweight is also a structural pattern, meaning that it aims to assist with both the structure of your objects and the relationships between them.</p>
<p>
So, how do we apply it to JavaScript?
</p>
<p>
There are two ways in which the Flyweight pattern can be applied. The first is on the data-layer, where we deal with the concept of large quantities of similar objects stored in memory. The second is on the DOM-layer where the flyweight can be used as a central event-manager to avoid attaching event handlers to every child element in a parent container you wish to have some similar behaviour.</p>
<p>
As the data-layer is where the flyweight pattern is most used traditionally, we'll take a look at this first.</p>
<h2>Flyweight and the data layer</h2>
<p>
For this application, there are a few more concepts around the classical flyweight pattern that we need to be aware of. In the Flyweight pattern there's a concept of two states - intrinsic and extrinsic. Intrinsic information may be required by internal methods in your objects which they absolutely can't function without. Extrinsic information can however be removed and stored externally.</p>
<p>
Objects with the same intrinsic data can be replaced with a single shared object, created by a factory method, meaning we're able to reduce the overall quantity of objects down significantly. The benefit of this is that we're able to keep an eye on objects that have already been instantiated so that new copies are only ever created should the intrinsic state differ from the object we already have.</p>
<p>
We use a manager to handle the extrinsic states. How this is implemented can vary, however as Dustin Diaz correctly points out in Pro JavaScript Design patterns, one approach to this to have the manager object contain a central database of the extrinsic states and the flyweight objects which they belong to.</p>
<h2>Converting code to use the Flyweight pattern</h2>
<p>
Let's now demonstrate some of these concepts using the idea of a system to manage all of the books in a library. The important meta-data for each book could probably be broken down as follows:</p>
<ul>
<li>ID</li>
<li>Title</li>
<li>Author</li>
<li>Genre</li>
<li>Page count</li>
<li>Publisher ID</li>
<li>ISBN</li>