SlideShare a Scribd company logo
Javascript Design Patterns Zohar Arad. April 2010
Javascript Design Patterns Singleton Module Engine Event-driven Templates
Why do we need design patterns?
To make our lives as programmers easier!
Singleton
Singleton A Singleton is an object in our programming scope that has ONLY one instance. Examples: Logger Window / Modal Reporter
Singleton Syntax: var Logger = {      initialized : false ,       initialize : function (){....},      getInstance : function (){          if(! this .initialized){              this .initialize();          }          return  this ;      }  }
Module
Module A Module is an object that can be instantiated but is not inheritable. Useful for any reusable, self-contained logical unit. Fast, slim and does not rely on external libraries. Examples: XHR handling Programmable DOM representation Almost anything your heart desires
Module var  Module =  function (o){     if(typeof o !== 'object'){          return  false;     }      return function (){         for(prop in o){             if(o.hasOwnProperty(prop)){                  this [prop] = o[prop];             }         }         if(typeof  this [ 'initialize' ] ==  'function' ){              this .initialize.apply( this ,arguments);         }          return this ;     } }
Module var  MyModule =  new  Module({      initialize: function (params){....},      doSomething: function (){....},      prop: 'value'   }); var  m =  new  Module();
Engine
Engine An engine is a callable that implements a unique internal logic and exposes a uniform API to the consumer (much like a Facade). Key advantages: Separation of logic from action Overridable Plugable Graceful error-handling   Examples: Modal window Media player
Engine var  ModalWindow =  new  Module({      initialize: function (){....},      call: function (engine,arg){          var engine = Consumer.Engines[engine];          if( typeof  engine ==  'function' ){              engine. call ( this ,arg)       }  }); Consumer.Engines = {      alert: function (){....},      prompt: function (){....},      confirm: function (){....}  }
Event-driven
Event-driven Event-driven programming uses DOM events as means of communication between separate pieces of code. Rational: Decoupling and separation of concerns No direct calls to functionality on the page No run-time errors due to missing functions Excellent for Flash-to-Javascript handling   Examples: state-to-action handling inter-object communication Flash-to-Javascript using window.fireEvent   * relies on external JS library to handle DOM events
Event-driven AS3: public function  stateChanged(state: String ):void{      var func: String  = ' window.fireEvent("stateChanged",                         ["'+ state +'"]) ';       ExternalInterface.call (func); } Javascript: window .addEvent('stateChanged', function (state){.....});
Event-driven var  Activity =  new  Class({      Implements: Events ,      doAction: function (action){          this .fireEvent('stateChanged',[action]);      }  }); var  Handler =  new  Class({      initialize: function (){          var  activity =  new  Activity();          activity.addEvent('stateChanged',                                           this .onStateChange.bind( this ));      },      onStateChange: function (action){          //...do something      }  });
Templates
Templates Used for handling repeat string-manipulation that produces large snippets of HTML. Rational: Saves on DOM-fragment handling Keeps DOM structure in one place Easy to make changes   Examples: Dynamic parsing of XHR response Manipulation of pre-defined DOM structuresr
Templates var  SomeClass = new Class({      onXHRResponse: function (data){          var  json = JSON.decode(data);           var  html = ''          var  t = '';          for (item  in  json){              if (!json.hasOwnProperty(item))  continue ;              var  i = json[item]              t = SomeClass.Template;               for (prop  in  i){                  if (!i.hasOwnProperty(prop))  continue ;                  var  re =  new  RegExp( '__' +prop+ '__' , 'gi' );                  t = t. replace (re,i[prop]);              }              html =+ t;          }          $('someElement').set('html',html);      }  }); SomeClass.Template =  '<a href=&quot;__url__&quot; title=&quot;__title__&quot;><img src=&quot;__src__&quot; alt=&quot;__title__&quot; /></a>' ;
Templates //response structure: { link1 :{url:'someurl',title:'sometitle',src:'somesrc', link2 :{url:'someurl',title:'sometitle',src:'somesrc', link3 :{url:'someurl',title:'sometitle',src:'somesrc', link4 :{url:'someurl',title:'sometitle',src:'somesrc'   }
Demo A demo containing the patterns discussed in the presentation can be found on  http://tinyb.cn/2vg

More Related Content

What's hot (20)

PPTX
Javascript basics for automation testing
Vikas Thange
 
PPT
Lecture05
elearning_portal
 
PPTX
Intro to Javascript
Anjan Banda
 
PDF
Java 8 Hipster slides
Oleg Prophet
 
PDF
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
PDF
JavaScript Core
François Sarradin
 
PDF
Javascript & Ajax Basics
Richard Paul
 
PPT
Cappuccino @ JSConf 2009
tolmasky
 
PPTX
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
PDF
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
PDF
javascript objects
Vijay Kalyan
 
PPT
JavaScript Basics
Mats Bryntse
 
PDF
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
PDF
JavaScript Execution Context
Juan Medina
 
PPSX
Javascript variables and datatypes
Varun C M
 
PDF
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
PPT
Javascript
Manav Prasad
 
PPTX
Advanced JavaScript Concepts
Naresh Kumar
 
PDF
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Javascript basics for automation testing
Vikas Thange
 
Lecture05
elearning_portal
 
Intro to Javascript
Anjan Banda
 
Java 8 Hipster slides
Oleg Prophet
 
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
JavaScript Core
François Sarradin
 
Javascript & Ajax Basics
Richard Paul
 
Cappuccino @ JSConf 2009
tolmasky
 
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
javascript objects
Vijay Kalyan
 
JavaScript Basics
Mats Bryntse
 
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
JavaScript Execution Context
Juan Medina
 
Javascript variables and datatypes
Varun C M
 
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswift
Tomohiro Kumagai
 
Javascript
Manav Prasad
 
Advanced JavaScript Concepts
Naresh Kumar
 
JavaScript: Variables and Functions
Jussi Pohjolainen
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 

Viewers also liked (6)

KEY
Architecting single-page front-end apps
Zohar Arad
 
KEY
Message in a Bottle
Zohar Arad
 
PDF
Rolling Your Own CSS Methodology
FITC
 
PPT
CSS Methodology
Zohar Arad
 
KEY
Introduction to HAML
Zohar Arad
 
PDF
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
Jer Clarke
 
Architecting single-page front-end apps
Zohar Arad
 
Message in a Bottle
Zohar Arad
 
Rolling Your Own CSS Methodology
FITC
 
CSS Methodology
Zohar Arad
 
Introduction to HAML
Zohar Arad
 
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
Jer Clarke
 
Ad

Similar to Javascript Design Patterns (20)

PPTX
Javascript Design Patterns
Iván Fernández Perea
 
PDF
Introduction to JavaScript design patterns
Jeremy Duvall
 
PDF
The Beauty of Java Script
Michael Girouard
 
PPT
Eugene Andruszczenko: jQuery
Refresh Events
 
PPT
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
PDF
Javascript coding-and-design-patterns
Hernan Mammana
 
PDF
Scalable JavaScript Design Patterns
Addy Osmani
 
PDF
The Beauty Of Java Script V5a
rajivmordani
 
PPT
JavaScript & Dom Manipulation
Mohammed Arif
 
PPTX
JS Essence
Uladzimir Piatryka
 
PPTX
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PPTX
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Fabio Franzini
 
PDF
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
PDF
Building a JavaScript Library
jeresig
 
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
PDF
Александр Белецкий "Архитектура Javascript приложений"
Agile Base Camp
 
PDF
Javascript Design Patterns
Subramanyan Murali
 
PPTX
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
PDF
Design patterns in javascript
Ayush Sharma
 
Javascript Design Patterns
Iván Fernández Perea
 
Introduction to JavaScript design patterns
Jeremy Duvall
 
The Beauty of Java Script
Michael Girouard
 
Eugene Andruszczenko: jQuery
Refresh Events
 
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
Javascript coding-and-design-patterns
Hernan Mammana
 
Scalable JavaScript Design Patterns
Addy Osmani
 
The Beauty Of Java Script V5a
rajivmordani
 
JavaScript & Dom Manipulation
Mohammed Arif
 
JS Essence
Uladzimir Piatryka
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Codemotion 2013 - Designing complex applications using html5 and knockoutjs
Fabio Franzini
 
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Building a JavaScript Library
jeresig
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Александр Белецкий "Архитектура Javascript приложений"
Agile Base Camp
 
Javascript Design Patterns
Subramanyan Murali
 
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
Design patterns in javascript
Ayush Sharma
 
Ad

Recently uploaded (20)

PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
July Patch Tuesday
Ivanti
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Biography of Daniel Podor.pdf
Daniel Podor
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 

Javascript Design Patterns

  • 1. Javascript Design Patterns Zohar Arad. April 2010
  • 2. Javascript Design Patterns Singleton Module Engine Event-driven Templates
  • 3. Why do we need design patterns?
  • 4. To make our lives as programmers easier!
  • 6. Singleton A Singleton is an object in our programming scope that has ONLY one instance. Examples: Logger Window / Modal Reporter
  • 7. Singleton Syntax: var Logger = {     initialized : false ,     initialize : function (){....},     getInstance : function (){         if(! this .initialized){             this .initialize();         }         return this ;      } }
  • 9. Module A Module is an object that can be instantiated but is not inheritable. Useful for any reusable, self-contained logical unit. Fast, slim and does not rely on external libraries. Examples: XHR handling Programmable DOM representation Almost anything your heart desires
  • 10. Module var Module = function (o){     if(typeof o !== 'object'){         return false;     }     return function (){         for(prop in o){             if(o.hasOwnProperty(prop)){                 this [prop] = o[prop];             }         }         if(typeof this [ 'initialize' ] == 'function' ){             this .initialize.apply( this ,arguments);         }         return this ;     } }
  • 11. Module var MyModule = new Module({     initialize: function (params){....},     doSomething: function (){....},     prop: 'value' }); var m = new Module();
  • 13. Engine An engine is a callable that implements a unique internal logic and exposes a uniform API to the consumer (much like a Facade). Key advantages: Separation of logic from action Overridable Plugable Graceful error-handling   Examples: Modal window Media player
  • 14. Engine var ModalWindow = new Module({     initialize: function (){....},     call: function (engine,arg){         var engine = Consumer.Engines[engine];         if( typeof engine == 'function' ){             engine. call ( this ,arg)     } }); Consumer.Engines = {     alert: function (){....},     prompt: function (){....},     confirm: function (){....} }
  • 16. Event-driven Event-driven programming uses DOM events as means of communication between separate pieces of code. Rational: Decoupling and separation of concerns No direct calls to functionality on the page No run-time errors due to missing functions Excellent for Flash-to-Javascript handling   Examples: state-to-action handling inter-object communication Flash-to-Javascript using window.fireEvent   * relies on external JS library to handle DOM events
  • 17. Event-driven AS3: public function stateChanged(state: String ):void{     var func: String = ' window.fireEvent(&quot;stateChanged&quot;,                         [&quot;'+ state +'&quot;]) ';     ExternalInterface.call (func); } Javascript: window .addEvent('stateChanged', function (state){.....});
  • 18. Event-driven var Activity = new Class({     Implements: Events ,     doAction: function (action){         this .fireEvent('stateChanged',[action]);     } }); var Handler = new Class({     initialize: function (){         var activity = new Activity();         activity.addEvent('stateChanged',                                          this .onStateChange.bind( this ));     },      onStateChange: function (action){         //...do something     } });
  • 20. Templates Used for handling repeat string-manipulation that produces large snippets of HTML. Rational: Saves on DOM-fragment handling Keeps DOM structure in one place Easy to make changes   Examples: Dynamic parsing of XHR response Manipulation of pre-defined DOM structuresr
  • 21. Templates var SomeClass = new Class({     onXHRResponse: function (data){         var json = JSON.decode(data);         var html = ''         var t = '';         for (item in json){             if (!json.hasOwnProperty(item)) continue ;             var i = json[item]             t = SomeClass.Template;             for (prop in i){                  if (!i.hasOwnProperty(prop)) continue ;                  var re = new RegExp( '__' +prop+ '__' , 'gi' );                 t = t. replace (re,i[prop]);             }             html =+ t;         }         $('someElement').set('html',html);      } }); SomeClass.Template = '<a href=&quot;__url__&quot; title=&quot;__title__&quot;><img src=&quot;__src__&quot; alt=&quot;__title__&quot; /></a>' ;
  • 22. Templates //response structure: { link1 :{url:'someurl',title:'sometitle',src:'somesrc', link2 :{url:'someurl',title:'sometitle',src:'somesrc', link3 :{url:'someurl',title:'sometitle',src:'somesrc', link4 :{url:'someurl',title:'sometitle',src:'somesrc'  }
  • 23. Demo A demo containing the patterns discussed in the presentation can be found on http://tinyb.cn/2vg