SlideShare a Scribd company logo
1 of 28
Download to read offline
JavaScript Design Patterns
Itinerary 
1. What are patterns? 
2. Why should we use them? 
3. Prerequisites 
4. Modules 
5. Facades 
6. Mediators
What is a Pattern? 
• A reusable solution that can be applied to commonly 
occurring problems in software design. 
Patterns are proven solutions. 
Patterns are reusable. 
Patterns are expressive. 
• Socialized in our industry by the legendary GoF tome of 
software patterns. But from whence did they originally 
come?
• Christopher Alexander (born 
October 4, 1936 in Vienna) 
• Cambridge University, BA in 
Architecture, MS in 
Mathematics. PhD from Harvard 
in Architecture. 
• “Notes on the Synthesis of Form” 
was required reading in CS 
throughout the 60’s. 
• “A Pattern Language” greatly 
influenced the design patterns 
movement.
Three Kinds 
• Creational: Methodologies for controlling the creation 
process of objects. In classical languages these are 
prolific. 
• Structural: Methodologies for organizing code into 
minimally coupled functional units and realize 
relationships between different objects. 
• Behavioral: Methodologies that focus on streamlining 
communication between disparate objects.
Why Patterns? 
• Patterns can encourage us to code in a more structured 
and organized fashion. 
• Patterns can provide generalized solutions which are not 
tied to a specific problem, and some facilitate DRY 
principles. 
• Patterns are supported by a larger force than the individual 
developer. 
• Patterns create a language by which developers may 
quickly communicate.
A Quick Experiment 
• Internal sensors are detecting a lifesign on deck 16, 
section 3, Jeffries tube junction 16C4-5. It appears 
to be a cat. 
• What the strag will think is that any man that can hitch 
the length and breadth of the Galaxy, rough it, slum it, 
struggle against terrible odds, win through and still know 
where his towel is, is clearly a man to be reckoned with. 
• Patterns build a vocabulary between developers and 
facilitate better communication. Writing code is an 
exercise in communication.
Prerequisites 
• JavaScript is classless; everything is an object. Many 
“classical” design patterns do not apply or need be 
modified to map appropriately. 
! var myObjectLiteral = { ! 
!! variableKey: variableValue,! 
!! functionKey: function () {! 
! // ...! 
!! }! 
! }; 
<= Scoping and Closures 
Object literal notation => 
! 
function makeAdder(x) {! 
var numAddersMade = 0;! 
return function(y) {! 
numAddersMade++;! 
return x + y;! 
};! 
}! !
Three Interoperating Patterns 
Modules 
Facades 
Mediators
The Module Pattern 
• Ubiquitous—you’ve likely already seen and/or used them. 
Almost every major framework uses some flavor of 
modules. 
• There are many different flavors. We’ll go through only a 
couple of them. 
• In all versions the central idea remains constant: group 
related functionality. This is the separation of concerns 
ideology. 
• Let’s take a look at a simple implementation.
! 
var myNamespace = (function () {! 
! 
var myPrivateVar, myPrivateMethod;! 
! 
// A private counter variable! 
myPrivateVar = 0;! 
! 
// A private function which logs any arguments! 
myPrivateMethod = function( foo ) {! 
console.log( foo );! 
};! 
! 
return {! 
! 
// A public variable! 
myPublicVar: "foo",! 
! 
// A public function utilizing privates! 
myPublicFunction: function( bar ) {! 
! 
// Increment our private counter! 
myPrivateVar++;! 
! 
// Call our private method using bar! 
myPrivateMethod( bar );! 
! 
}! 
};! 
! 
})();!
! 
var basketModule = (function() {! 
var basket = []; //private! 
return { //exposed to public! 
addItem: function(values) {! 
basket.push(values);! 
},! 
getItemCount: function() {! 
return basket.length;! 
},! 
getTotal: function(){! 
var q = this.getItemCount(),p=0;! 
while(q--){! 
p+= basket[q].price; ! 
}! 
return p;! 
}! 
}! 
}());! 
! 
public class Basket {! 
! private List<Product> products;! 
! public void addItem(Product p) { //... }! 
! public int getItemCount() { //... }! 
! public double getTotal() { //... }! 
}! 
!! 
If you’re familiar with 
classical compiled 
languages: the two 
pieces of code to the left 
are functionally equivalent. 
Modules allow hiding— 
that is keeping your 
internals private.
Handling Dependencies 
! 
(function ($) {! 
// Module impl goes here! 
return {! 
// Return module interface here! 
}! 
}(jQuery));! 
! 
! 
// myModule is now in global scope! 
var myModule = (function($) {! 
// Module impl goes here! 
return {! 
// Return module interface here! 
}! 
}(jQuery));! 
! 
Importing other modules 
is quite simple. 
As is exporting your 
existing module.
CommonJS 
• There exists a standard definition for modules called 
Asynchronous Module Definition (AMD) built by the 
original CommonJS mailing list participants. 
• AMD is a maintained standard that has a good 
following: https://github.com/amdjs/amdjs-api/wiki/ 
AMD 
• Key dependency: no modules may be synchronously 
loaded. The order should not be significant.
//Calling define with module ID, dependency array, ! 
//and factory function! 
define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {! 
! 
//Define the module value by returning a value.! 
return function () {};! 
}); 
• Reserves the word “define” for creating modules and 
describing relationships between them. 
• Supported by major frameworks such as Angular.js (look 
familiar?). 
angular.module("myModule").factory("myNamespace.myModule", MyModule);! 
MyModule.$inject = [ "$http", "$cookies" ];! 
function MyModule($http, $cookies) { //... ! 
}
Augmentation 
• Allows for implementations of a single 
module to exist in multiple files. 
• Loose augmentation: modules can be 
loaded in any order. Overriding methods is 
not possible. 
module.base.js 
module.f1.js 
module.f2.js 
module.patch1.js 
! 
var myModule = (function(module) {! 
var privateMethod = function() { //... }! 
return {! 
publicApi : privateMethod! 
}! 
}(myModule || {}));! 
!! 
Advanced Topics
var myModule = (function (me) {! 
! var old_moduleMethod = me.moduleMethod;! 
! 
! me.moduleMethod = function () {! 
! ! // method override! 
! };! 
! 
! return me;! 
}(myModule || {})); 
Tight augmentation 
enables method 
overrides. 
• There are novel uses for both tight and loose augmentation. 
We could push a hot-patch without breaking existing code. 
• Tight augmentation requires an order to loading. This breaks 
the AMD spec, but buys you a lot of power. 
• Super advanced topic: it’s also possible to share state across 
files: http://bit.ly/18byc2Q 
Advanced Topics
Hotfixes 
• Tight augmentation can be used to efficiently hot fix 
bugs so long as the affected module supports it. 
Implement fix as a 
module override 
Apply fix through 
HTML script 
imports 
var myModule = (function (me) {! 
! var broken = me.foo;! 
! 
! me.foo = function () {! 
! ! // patch the issue here! 
! };! 
! 
! return me;! 
}(myModule || {})); 
<script src="myApp.js" />! 
<!-- Temporary fix! -->! 
<script src="myPatch.js" /> 
Save as a patch file. Order matters! 
Deploy, but now 
fix the issue for 
real :D.
Revealing Module 
• Simply a way of organizing 
your code so it looks nicer. 
• Easy to read and understand 
the interface provided by the 
module. 
• Watch out: if a private 
function refers to a public 
function, you possibly cannot 
override the public function if 
a patch is necessary. 
! 
var basketModule = (function() {! 
var basket = []; //private! 
! 
var _addItem = function(values) {! 
basket.push(values);! 
}! 
! 
var _getItemCount = function() {! 
return basket.length;! 
}! 
! 
var _getTotal = function() {! 
var q = this.getItemCount(),p=0;! 
while(q--){! 
p+= basket[q].price; ! 
}! 
return p;! 
}! 
! 
// Nice, clean interface! 
return { ! 
addItem: _addItem,! 
getItemCount: _getItemCount,! 
getTotal: _getTotal! 
}! 
}());!
Facades 
• A facade is a limited abstraction on top of a more 
complex body of code. 
• Consumers interacting with the facade often interact 
with a very simple API hiding a complex sub-system. 
• A facade also decouples interfaces from 
implementation—allowing for hot-swappable sub-systems. 
• Only expose existing behavior.
var ecommerceFacade = (function (basketModule, promoModule) {! 
return {! 
getTotal : function () {! 
return basketModule.getTotal() * (1 - promoModule.getPercentDiscount());! 
},! 
listPromoCodes : promoModule.listPromoCodes,! 
getPercentDiscount : promoModule.getPercentDiscount,! 
getItemCount : basketModule.getItemCount,! 
addItem : basketModule.addItem,! 
addPromoCode : basketModule.addPromoCode! 
}! 
}(basketModule, promoModule));! 
Facades should be used to further decouple business logic by 
supplying a common, well known interface on existing components. 
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;! 
}! 
};! 
They are often useful for 
hiding ugly browser-based 
logic switches.
Mediators 
• Mediators encapsulate how a set of objects interact. 
• This promotes loose coupling by keeping objects from 
referring to each other explicitly and allows you to vary 
their interaction independently. 
• Mediators promote high cohesion by keeping code for 
interaction between modules encapsulated. 
• Think of them as “workflow” facilitators.
Example Flow 
Mediators encapsulate complex interactions between actors 
(modules) in the system. The facilitate communication without the 
need for directly referencing the desired component. 
Order Mediator 
E-Commerce 
Facade 
Basket Module Promo Module Order Service 
getTotal() 
submitOrder()
Pub/Sub Subtleties 
• Mediators often look like event aggregators. They can 
be confused with other similar patterns such as 
Observer. 
• The difference between mediators and other pub/sub 
paradigms is simply this: where is the application logic 
coded? 
• Mediators are “white gloved” business logic, while 
event aggregators are “fire and forget.”
Which Pattern(s)? 
• Build a component that handles interaction with a user 
profile service. Actions include logging in via token based 
authentication and performing CRUD on user data. 
• Build a payment processing component that supports 
multiple payment types like PayPal, credit card, or credit 
card reward points from your partner systems. 
• Build a component that drives an interactive car designer. 
Note that some accessories and features may only be 
available at specific trim levels and geographical locations.
Parting Words 
• Pick the right tool for the job in your circumstances. 
• Know modules inside and out. Settle on one paradigm 
and don’t deviate. 
• Mediators are very slick—consider them when the 
relationships between objects becomes complex. 
• These patterns can be used inside frameworks too 
(Angular, Backbone, etcetera).
Questions? 
Next time: Promises!

More Related Content

What's hot

Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz Nowak
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End DevelopmentWalid Ashraf
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy stepsprince Loffar
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming languageMarco Cedaro
 
مقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزمقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزrailsbootcamp
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2kaven yan
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOMSukrit Gupta
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용KyeongMook "Kay" Cha
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 

What's hot (20)

Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
 
مقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزمقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلز
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOM
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 

Viewers also liked

Torba kanun sunum ankara
Torba kanun sunum ankaraTorba kanun sunum ankara
Torba kanun sunum ankararmznyldz
 
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)rmznyldz
 
Reyes Católicos: Segundo de Bachiller, PAU
Reyes Católicos: Segundo de Bachiller, PAUReyes Católicos: Segundo de Bachiller, PAU
Reyes Católicos: Segundo de Bachiller, PAUAndrés Ruz Nieto
 
Heat transfer brochure
Heat transfer brochureHeat transfer brochure
Heat transfer brochureNuno Martins
 
Game Sense Approach
Game Sense ApproachGame Sense Approach
Game Sense ApproachMariah-A
 
Weekly commodity report - 22nd October, 2014
Weekly commodity report - 22nd October, 2014Weekly commodity report - 22nd October, 2014
Weekly commodity report - 22nd October, 2014Darshith H S
 
#Capemarketing sales mini masterclass
#Capemarketing sales mini masterclass #Capemarketing sales mini masterclass
#Capemarketing sales mini masterclass outshine_SA
 
Torba kanun sunum
Torba kanun sunumTorba kanun sunum
Torba kanun sunumrmznyldz
 
Borcu yoktur
Borcu yokturBorcu yoktur
Borcu yokturrmznyldz
 

Viewers also liked (14)

Contents
ContentsContents
Contents
 
Plagiarism
PlagiarismPlagiarism
Plagiarism
 
Torba kanun sunum ankara
Torba kanun sunum ankaraTorba kanun sunum ankara
Torba kanun sunum ankara
 
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)
6552 sayılı kanunun SGK Yapılandırma sunumu 02 01 2014 (3)
 
Reyes Católicos: Segundo de Bachiller, PAU
Reyes Católicos: Segundo de Bachiller, PAUReyes Católicos: Segundo de Bachiller, PAU
Reyes Católicos: Segundo de Bachiller, PAU
 
Heat transfer brochure
Heat transfer brochureHeat transfer brochure
Heat transfer brochure
 
Game Sense Approach
Game Sense ApproachGame Sense Approach
Game Sense Approach
 
Weekly commodity report - 22nd October, 2014
Weekly commodity report - 22nd October, 2014Weekly commodity report - 22nd October, 2014
Weekly commodity report - 22nd October, 2014
 
#Capemarketing sales mini masterclass
#Capemarketing sales mini masterclass #Capemarketing sales mini masterclass
#Capemarketing sales mini masterclass
 
Gebeurtenis
GebeurtenisGebeurtenis
Gebeurtenis
 
Tugas 2 mtk 2
Tugas 2 mtk 2Tugas 2 mtk 2
Tugas 2 mtk 2
 
Torba kanun sunum
Torba kanun sunumTorba kanun sunum
Torba kanun sunum
 
Game sense
Game sense Game sense
Game sense
 
Borcu yoktur
Borcu yokturBorcu yoktur
Borcu yoktur
 

Similar to Introduction to JavaScript design patterns

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applicationsDivyanshGupta922023
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsRuth Marvin
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 

Similar to Introduction to JavaScript design patterns (20)

Refactoring
RefactoringRefactoring
Refactoring
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
jquery summit presentation for large scale javascript applications
jquery summit  presentation for large scale javascript applicationsjquery summit  presentation for large scale javascript applications
jquery summit presentation for large scale javascript applications
 
Html5 Overview
Html5 OverviewHtml5 Overview
Html5 Overview
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 

Introduction to JavaScript design patterns

  • 2.
  • 3. Itinerary 1. What are patterns? 2. Why should we use them? 3. Prerequisites 4. Modules 5. Facades 6. Mediators
  • 4. What is a Pattern? • A reusable solution that can be applied to commonly occurring problems in software design. Patterns are proven solutions. Patterns are reusable. Patterns are expressive. • Socialized in our industry by the legendary GoF tome of software patterns. But from whence did they originally come?
  • 5. • Christopher Alexander (born October 4, 1936 in Vienna) • Cambridge University, BA in Architecture, MS in Mathematics. PhD from Harvard in Architecture. • “Notes on the Synthesis of Form” was required reading in CS throughout the 60’s. • “A Pattern Language” greatly influenced the design patterns movement.
  • 6. Three Kinds • Creational: Methodologies for controlling the creation process of objects. In classical languages these are prolific. • Structural: Methodologies for organizing code into minimally coupled functional units and realize relationships between different objects. • Behavioral: Methodologies that focus on streamlining communication between disparate objects.
  • 7. Why Patterns? • Patterns can encourage us to code in a more structured and organized fashion. • Patterns can provide generalized solutions which are not tied to a specific problem, and some facilitate DRY principles. • Patterns are supported by a larger force than the individual developer. • Patterns create a language by which developers may quickly communicate.
  • 8. A Quick Experiment • Internal sensors are detecting a lifesign on deck 16, section 3, Jeffries tube junction 16C4-5. It appears to be a cat. • What the strag will think is that any man that can hitch the length and breadth of the Galaxy, rough it, slum it, struggle against terrible odds, win through and still know where his towel is, is clearly a man to be reckoned with. • Patterns build a vocabulary between developers and facilitate better communication. Writing code is an exercise in communication.
  • 9. Prerequisites • JavaScript is classless; everything is an object. Many “classical” design patterns do not apply or need be modified to map appropriately. ! var myObjectLiteral = { ! !! variableKey: variableValue,! !! functionKey: function () {! ! // ...! !! }! ! }; <= Scoping and Closures Object literal notation => ! function makeAdder(x) {! var numAddersMade = 0;! return function(y) {! numAddersMade++;! return x + y;! };! }! !
  • 10. Three Interoperating Patterns Modules Facades Mediators
  • 11. The Module Pattern • Ubiquitous—you’ve likely already seen and/or used them. Almost every major framework uses some flavor of modules. • There are many different flavors. We’ll go through only a couple of them. • In all versions the central idea remains constant: group related functionality. This is the separation of concerns ideology. • Let’s take a look at a simple implementation.
  • 12. ! var myNamespace = (function () {! ! var myPrivateVar, myPrivateMethod;! ! // A private counter variable! myPrivateVar = 0;! ! // A private function which logs any arguments! myPrivateMethod = function( foo ) {! console.log( foo );! };! ! return {! ! // A public variable! myPublicVar: "foo",! ! // A public function utilizing privates! myPublicFunction: function( bar ) {! ! // Increment our private counter! myPrivateVar++;! ! // Call our private method using bar! myPrivateMethod( bar );! ! }! };! ! })();!
  • 13. ! var basketModule = (function() {! var basket = []; //private! return { //exposed to public! addItem: function(values) {! basket.push(values);! },! getItemCount: function() {! return basket.length;! },! getTotal: function(){! var q = this.getItemCount(),p=0;! while(q--){! p+= basket[q].price; ! }! return p;! }! }! }());! ! public class Basket {! ! private List<Product> products;! ! public void addItem(Product p) { //... }! ! public int getItemCount() { //... }! ! public double getTotal() { //... }! }! !! If you’re familiar with classical compiled languages: the two pieces of code to the left are functionally equivalent. Modules allow hiding— that is keeping your internals private.
  • 14. Handling Dependencies ! (function ($) {! // Module impl goes here! return {! // Return module interface here! }! }(jQuery));! ! ! // myModule is now in global scope! var myModule = (function($) {! // Module impl goes here! return {! // Return module interface here! }! }(jQuery));! ! Importing other modules is quite simple. As is exporting your existing module.
  • 15. CommonJS • There exists a standard definition for modules called Asynchronous Module Definition (AMD) built by the original CommonJS mailing list participants. • AMD is a maintained standard that has a good following: https://github.com/amdjs/amdjs-api/wiki/ AMD • Key dependency: no modules may be synchronously loaded. The order should not be significant.
  • 16. //Calling define with module ID, dependency array, ! //and factory function! define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {! ! //Define the module value by returning a value.! return function () {};! }); • Reserves the word “define” for creating modules and describing relationships between them. • Supported by major frameworks such as Angular.js (look familiar?). angular.module("myModule").factory("myNamespace.myModule", MyModule);! MyModule.$inject = [ "$http", "$cookies" ];! function MyModule($http, $cookies) { //... ! }
  • 17. Augmentation • Allows for implementations of a single module to exist in multiple files. • Loose augmentation: modules can be loaded in any order. Overriding methods is not possible. module.base.js module.f1.js module.f2.js module.patch1.js ! var myModule = (function(module) {! var privateMethod = function() { //... }! return {! publicApi : privateMethod! }! }(myModule || {}));! !! Advanced Topics
  • 18. var myModule = (function (me) {! ! var old_moduleMethod = me.moduleMethod;! ! ! me.moduleMethod = function () {! ! ! // method override! ! };! ! ! return me;! }(myModule || {})); Tight augmentation enables method overrides. • There are novel uses for both tight and loose augmentation. We could push a hot-patch without breaking existing code. • Tight augmentation requires an order to loading. This breaks the AMD spec, but buys you a lot of power. • Super advanced topic: it’s also possible to share state across files: http://bit.ly/18byc2Q Advanced Topics
  • 19. Hotfixes • Tight augmentation can be used to efficiently hot fix bugs so long as the affected module supports it. Implement fix as a module override Apply fix through HTML script imports var myModule = (function (me) {! ! var broken = me.foo;! ! ! me.foo = function () {! ! ! // patch the issue here! ! };! ! ! return me;! }(myModule || {})); <script src="myApp.js" />! <!-- Temporary fix! -->! <script src="myPatch.js" /> Save as a patch file. Order matters! Deploy, but now fix the issue for real :D.
  • 20. Revealing Module • Simply a way of organizing your code so it looks nicer. • Easy to read and understand the interface provided by the module. • Watch out: if a private function refers to a public function, you possibly cannot override the public function if a patch is necessary. ! var basketModule = (function() {! var basket = []; //private! ! var _addItem = function(values) {! basket.push(values);! }! ! var _getItemCount = function() {! return basket.length;! }! ! var _getTotal = function() {! var q = this.getItemCount(),p=0;! while(q--){! p+= basket[q].price; ! }! return p;! }! ! // Nice, clean interface! return { ! addItem: _addItem,! getItemCount: _getItemCount,! getTotal: _getTotal! }! }());!
  • 21. Facades • A facade is a limited abstraction on top of a more complex body of code. • Consumers interacting with the facade often interact with a very simple API hiding a complex sub-system. • A facade also decouples interfaces from implementation—allowing for hot-swappable sub-systems. • Only expose existing behavior.
  • 22. var ecommerceFacade = (function (basketModule, promoModule) {! return {! getTotal : function () {! return basketModule.getTotal() * (1 - promoModule.getPercentDiscount());! },! listPromoCodes : promoModule.listPromoCodes,! getPercentDiscount : promoModule.getPercentDiscount,! getItemCount : basketModule.getItemCount,! addItem : basketModule.addItem,! addPromoCode : basketModule.addPromoCode! }! }(basketModule, promoModule));! Facades should be used to further decouple business logic by supplying a common, well known interface on existing components. 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;! }! };! They are often useful for hiding ugly browser-based logic switches.
  • 23. Mediators • Mediators encapsulate how a set of objects interact. • This promotes loose coupling by keeping objects from referring to each other explicitly and allows you to vary their interaction independently. • Mediators promote high cohesion by keeping code for interaction between modules encapsulated. • Think of them as “workflow” facilitators.
  • 24. Example Flow Mediators encapsulate complex interactions between actors (modules) in the system. The facilitate communication without the need for directly referencing the desired component. Order Mediator E-Commerce Facade Basket Module Promo Module Order Service getTotal() submitOrder()
  • 25. Pub/Sub Subtleties • Mediators often look like event aggregators. They can be confused with other similar patterns such as Observer. • The difference between mediators and other pub/sub paradigms is simply this: where is the application logic coded? • Mediators are “white gloved” business logic, while event aggregators are “fire and forget.”
  • 26. Which Pattern(s)? • Build a component that handles interaction with a user profile service. Actions include logging in via token based authentication and performing CRUD on user data. • Build a payment processing component that supports multiple payment types like PayPal, credit card, or credit card reward points from your partner systems. • Build a component that drives an interactive car designer. Note that some accessories and features may only be available at specific trim levels and geographical locations.
  • 27. Parting Words • Pick the right tool for the job in your circumstances. • Know modules inside and out. Settle on one paradigm and don’t deviate. • Mediators are very slick—consider them when the relationships between objects becomes complex. • These patterns can be used inside frameworks too (Angular, Backbone, etcetera).