SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
JAVASCRIPT
DESIGN
PATTERNS
BASED IN ADDY OSMANI’S BOOK
‘ESSENTIAL JAVASCRIPT & JQUERY DESIGN
PATTERNS’
PRESENTATION SCOPE
• Background.
• What is a Design Pattern?.
• Structure of a Design Pattern.
• Anti-patterns.
• Design Patterns in Javascript.
• MV* Patterns.
BACKGROUND
1977 First mention of
patterns in
engineering in 'A
Pattern Language' by
Christopher
Alexander.
1987 First studies about
applying patterns to
programming. Presented
at the OOPSLA
conference by Kent Beck
and Ward Cunningham
1995 'Design Patterns:
Elements Of Reusable
Object-Oriented
Software' by Erich
Gamma, Richard Helm,
Ralph Johnson and
John Vlissides so called
GoF
BACKGROUND
• 2002 Patterns of Enterprise Application Architecture
by Martin Fowler
• 2003 Enterprise Integration Patterns: Designing,
Building, and Deploying Messaging Solutions
by Gregor Hohpe and Bobby Woolf
• 2009 SOA Design Patterns by Thomas Erl
WHAT IS A DESIGN PATTERN?
1. A pattern is a general reusable solution to a commonly
occurring problem within a given context.
2. It is a description or template for how to solve a problem
that can be used in many different situation
REMEMBER …
A design pattern is not a finished design that can be
transformed directly into code
WHAT IS A DESIGN PATTERN?
1. Patterns are proven solutions.
Solid approaches to solving issues in
software development.
2. Patterns can be easily reused.
Less time about your code structure, more
time about solution logic
3. Patterns can be expressive.
Set structure and ‘vocabulary’ to the solution
presented. Communication is easier.
STRUCTURE OF A DESIGN PATTERN
• Pattern name and a description
• Context outline
• Problem statement.
• Solution.
• Design.
• Implementation.
• Illustrations.
• Examples.
• Co-requisites.
• Relations.
• Known usage.
• Discussions.
ANTI-PATTERNS
Term coined in 1995 by Andrew Koening in the C++ Report.
• Describe a bad solution to a particular problem which
resulted in a bad situation occurring
• Describe how to get out of said situation and how to go from
there to a good solution
The build Monkey Antipattern
DESIGN PATTERNS (IN JAVASCRIPT)
• Creational. How the entities should be created to
fit its purpose. Constructor, Factory, Abstract,
Prototype, Singleton and Builder.
• Structural. Simple ways of relationship between
different objects. Module, Decorator, Facade,
Flyweight, Adapter and Proxy
• Behavioral. improving or streamlining the
communication between disparate objects in a
system. Iterator, Mediator, Observer, Command
and Visitor.
CONSTRUCTOR AND PROTOTYPE
PATTERN.
Keep in mind that Javascript is a class-less programming language, but these
can be simulated usign functions.
function Car ( model,color,year ){
this.model = model;
this.color = 'silver';
this.year = '2012';
this.getInfo = function(){
return this.model + ' ' + this.year;
}
}
Constructor Pattern. Create new Car objects.
var civic = new Car( "Honda Civic" , "blue", 20000 );
Prototype Pattern. Functions in javascript have a property called a prototype.
Car.prototype.toString = function(){
return this.model + ” did " + this.miles + " miles";
};
MODULE PATTERN.
Group several related elements such as classes, singletons,
methods, globally used, into a simple object. It fakes classes in
Javascript.
Defined Richard Cornford in 2003 and popularized by Douglas
Crockford in his lectures.
Pros:
• Encapsulation, it gives us an API (public and private attributes or
methods),
• Avoid names conflicting with other function
• Easier debugging (public functions are named)
Cons:
• Difficult to refactor.
MODULE PATTERN.
var testModule = (function(){
var counter = 0;
var privateMethod = function() {
// do some very nasty stuff.
}
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value before reset:’+ counter);
counter = 0;
}
};
})();
REVEALING MODULE PATTERN.
Coined by by Christian Heilmann (Mozilla Foundation).
Pros:
• Sintax more consistent and easy to read.
• Easier to refactor.
var myRevealingModule = (function(){
var name = 'John Smith';
function updatePerson(){
name = 'John Smith Updated';
}
function setPerson (value) {
name = value;
}
return {
set: setPerson,
};
}());
OBSERVER OR PUB/SUB PATTERN.
• It is a design pattern which allows an object (known as a
subscriber) to watch another object (the publisher).
• Loose coupling, ability to break down our applications into
smaller, general manageability.
• Many implementation in Javascript.
• Ben Alman's Pub/Sub gist https://gist.github.com/661855
(recommended)
• Rick Waldron's jQuery-core style take on the above
https://gist.github.com/705311
• Peter Higgins' plugin http://github.com/phiggins42/bloody-
jquery-plugins/blob/master/pubsub.js.
• AppendTo's Pub/Sub in AmplifyJS http://amplifyjs.com
• Ben Truyman's gist https://gist.github.com/826794
OBSERVER OR PUB/SUB PATTERN.
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
q.publish = function( topic, args ) {
if ( !topics[topic] ) { return false; }
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);}
return this;
};
q.subscribe = function( topic, func ) {
if (!topics[topic]) { topics[topic] = []; }
var token = (++subUid).toString();
topics[topic].push({ token: token, func: func });
return token;
};
}( pubsub ));
COMMAND PATTERN
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.
(function(){
var CarManager = {
buyVehicle: function( model, id ){
return 'You have purchased Item '
+ id + ', a ' + model;
}};
})();
CarManager.execute = function (name) {
return CarManager[name] && CarManager[name].apply
(CarManager, [].slice.call(arguments, 1));
};
CarManager.execute("buyVehicle", "Ford Escort", "34232");
MV* PATTERNS
• Software Design pattern or Architecture design pattern?.
• Coined by Trygve Reenskaug during his time working on
Smalltalk-80 (1979) where it was initially called Model-View-
Controller-Editor.
• Variations:
• MVC. Model-View-Controller. Spine.js / Backbone.js (MVR)
• MVP. Model-View-Presenter. Backbone.js
• MVVM. Model-View-ViewModel. Knockout.js / Knockback.js
• It has been structuring desktop and server-side applications,
but it's only been in recent years that come to being applied to
JavaScript.
• http://addyosmani.github.com/todomvc/
BACKBONE.JS MVC, MVP OR MVR?
• Flexible framework to build Javascript web applications.
• Backbone.js doesn’t fit in any specific pattern.
• There is no controller in Backbone. Views and Routers instead.
• Backbone’s Architecture.
• Model. Extend from Model or Collection.
var Todo = Backbone.Model.extend({
defaults: {
content: "empty todo...",
done: false
},
// Ensure that each todo created has `content`.
initialize: function() {
if (!this.get("content")) {
this.set({"content": this.defaults.content});
}
}
});
BACKBONE.JS COLLECTIONS
• Model. Extend from Collection.
var User = Backbone.Collection.extend({
model: User,
url: 'https://api.twitter.com/1/user/show.json?id=7&callback=?',
parse: function(response) {
//console.log('parsing user ...');
return response;
}
});
BACKBONE.JS VIEW
• View. It can see as a a View, a Presenter or even a Controller.
var PageView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'doSearch'
},
initialize: function() {
this.template = _.template('<li><%= name %></li>');
_.bindAll(this, 'render', 'addItem');
this.('reset', function(collection) {
_this.$('#tweets').empty();
collection.each(function(tweet) {
_this.addItem(tweet);
});
});
this.render();
}, …
BACKBONE.JS VIEW CONT.
…
doSearch: function() {
var subject = $('#search').val() || 'Node.js';
this.tweets.url = 'http://search.twitter.com/ search.json?q=’
+ subject + '&rpp=8&callback=?';
this.tweets.fetch();
},
render: function() {
var html = template({
img: item.get('profile_image_url') ,
user: item.get('from_user_name'),
text: item.get('text') });
$('#tweets', this.el).append(html);
return this;
}
});
You also use templating within the View layer. (Mustache.js, Jquery.tmpl, ….).
BACKBONE.JS ROUTER
• Router. It may be seen as a pseudo-controller.
var myRouter = Backbone.Router.extend({
routes: {
"help": "help", // #help
"search/:query": "search", // #search/users
"search/:query/p:page": "search" // #search/users/p7
},
help: function() {
...
},
search: function(query, page) {
...
}
});
SPINE.JS. MVC LIBRARY.
• Controllers are considered the glue between
the Model and the View.
var PhotosController = Spine.Controller.sub({
init: function(){
this.item.bind("update", this.proxy(this.render));
this.item.bind("destroy", this.proxy(this.remove));
},
render: function(){
this.replace($("#photoTemplate").tmpl(this.item));
return this;
},
remove: function(){
this.el.remove();
this.release();
}
});
KNOCKOUT.JS MVVM
• Defined in 2005 by John Grossman for use with
Windows Presentation Foundation (WPF) and
Silverlight
• More clearly separate the development of user-
interfaces (UI) from that of the business logic and
behavior in an application.
• Make use of declarative data bindings to allow a
separation of work on Views from other layers. It
provides data-binding from the Model directly from
the View
• Based on Model View PresentationModel. Martin
Fowler wrote an article on PresentationModels
back in 2004
KNOCKOUT.JS MVVM
• Model. It uses the Observable property that can
notify subscribers about changes and automatically
detect dependencies
• View. A KnockoutJS View is simply a HTML
document with declarative bindings to link it to the
ViewModel
• ViewModel. The ViewModel can be considered a
specialized Controller that acts as a data converter.
It changes Model information into View information,
passing commands from the View to the Model.
KNOCKOUT.JS VIEWMODEL
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
this.capitalizeLastName = function() {
var currentVal = this.lastName();
this.lastName(currentVal.toUpperCase());
};
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
KNOCKOUT.JS VIEW
• Plain HTML
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeLastName">Go caps</button>

Más contenido relacionado

La actualidad más candente

RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019Fabio Biondi
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Angular data binding
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keywordPham Huy Tung
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium  Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium Zoe Gilbert
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to reactkiranabburi
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & StreamsEyal Vardi
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 

La actualidad más candente (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
React js
React jsReact js
React js
 
RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
React js
React jsReact js
React js
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium  Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
React and redux
React and reduxReact and redux
React and redux
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 

Destacado

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
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patternsThaichor Seng
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 

Destacado (6)

Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
OAuth
OAuthOAuth
OAuth
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Javascript
JavascriptJavascript
Javascript
 

Similar a 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
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JSBipin
 
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
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
Design patterns
Design patternsDesign patterns
Design patternsnisheesh
 
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSDeepu S Nath
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Ovadiah Myrgorod
 
From Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) AgainFrom Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) Againjonknapp
 
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Nicolas HAAN
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletonGeorge Nguyen
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture Jiby John
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 

Similar a Javascript Design Patterns (20)

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...
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
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
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
From Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) AgainFrom Backbone to Ember and Back(bone) Again
From Backbone to Ember and Back(bone) Again
 
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Final ppt
Final pptFinal ppt
Final ppt
 

Último

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Último (20)

Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

Javascript Design Patterns

  • 1. JAVASCRIPT DESIGN PATTERNS BASED IN ADDY OSMANI’S BOOK ‘ESSENTIAL JAVASCRIPT & JQUERY DESIGN PATTERNS’
  • 2. PRESENTATION SCOPE • Background. • What is a Design Pattern?. • Structure of a Design Pattern. • Anti-patterns. • Design Patterns in Javascript. • MV* Patterns.
  • 3. BACKGROUND 1977 First mention of patterns in engineering in 'A Pattern Language' by Christopher Alexander. 1987 First studies about applying patterns to programming. Presented at the OOPSLA conference by Kent Beck and Ward Cunningham 1995 'Design Patterns: Elements Of Reusable Object-Oriented Software' by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides so called GoF
  • 4. BACKGROUND • 2002 Patterns of Enterprise Application Architecture by Martin Fowler • 2003 Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions by Gregor Hohpe and Bobby Woolf • 2009 SOA Design Patterns by Thomas Erl
  • 5. WHAT IS A DESIGN PATTERN? 1. A pattern is a general reusable solution to a commonly occurring problem within a given context. 2. It is a description or template for how to solve a problem that can be used in many different situation REMEMBER … A design pattern is not a finished design that can be transformed directly into code
  • 6. WHAT IS A DESIGN PATTERN? 1. Patterns are proven solutions. Solid approaches to solving issues in software development. 2. Patterns can be easily reused. Less time about your code structure, more time about solution logic 3. Patterns can be expressive. Set structure and ‘vocabulary’ to the solution presented. Communication is easier.
  • 7. STRUCTURE OF A DESIGN PATTERN • Pattern name and a description • Context outline • Problem statement. • Solution. • Design. • Implementation. • Illustrations. • Examples. • Co-requisites. • Relations. • Known usage. • Discussions.
  • 8. ANTI-PATTERNS Term coined in 1995 by Andrew Koening in the C++ Report. • Describe a bad solution to a particular problem which resulted in a bad situation occurring • Describe how to get out of said situation and how to go from there to a good solution The build Monkey Antipattern
  • 9. DESIGN PATTERNS (IN JAVASCRIPT) • Creational. How the entities should be created to fit its purpose. Constructor, Factory, Abstract, Prototype, Singleton and Builder. • Structural. Simple ways of relationship between different objects. Module, Decorator, Facade, Flyweight, Adapter and Proxy • Behavioral. improving or streamlining the communication between disparate objects in a system. Iterator, Mediator, Observer, Command and Visitor.
  • 10. CONSTRUCTOR AND PROTOTYPE PATTERN. Keep in mind that Javascript is a class-less programming language, but these can be simulated usign functions. function Car ( model,color,year ){ this.model = model; this.color = 'silver'; this.year = '2012'; this.getInfo = function(){ return this.model + ' ' + this.year; } } Constructor Pattern. Create new Car objects. var civic = new Car( "Honda Civic" , "blue", 20000 ); Prototype Pattern. Functions in javascript have a property called a prototype. Car.prototype.toString = function(){ return this.model + ” did " + this.miles + " miles"; };
  • 11. MODULE PATTERN. Group several related elements such as classes, singletons, methods, globally used, into a simple object. It fakes classes in Javascript. Defined Richard Cornford in 2003 and popularized by Douglas Crockford in his lectures. Pros: • Encapsulation, it gives us an API (public and private attributes or methods), • Avoid names conflicting with other function • Easier debugging (public functions are named) Cons: • Difficult to refactor.
  • 12. MODULE PATTERN. var testModule = (function(){ var counter = 0; var privateMethod = function() { // do some very nasty stuff. } return { incrementCounter: function() { return counter++; }, resetCounter: function() { console.log('counter value before reset:’+ counter); counter = 0; } }; })();
  • 13. REVEALING MODULE PATTERN. Coined by by Christian Heilmann (Mozilla Foundation). Pros: • Sintax more consistent and easy to read. • Easier to refactor. var myRevealingModule = (function(){ var name = 'John Smith'; function updatePerson(){ name = 'John Smith Updated'; } function setPerson (value) { name = value; } return { set: setPerson, }; }());
  • 14. OBSERVER OR PUB/SUB PATTERN. • It is a design pattern which allows an object (known as a subscriber) to watch another object (the publisher). • Loose coupling, ability to break down our applications into smaller, general manageability. • Many implementation in Javascript. • Ben Alman's Pub/Sub gist https://gist.github.com/661855 (recommended) • Rick Waldron's jQuery-core style take on the above https://gist.github.com/705311 • Peter Higgins' plugin http://github.com/phiggins42/bloody- jquery-plugins/blob/master/pubsub.js. • AppendTo's Pub/Sub in AmplifyJS http://amplifyjs.com • Ben Truyman's gist https://gist.github.com/826794
  • 15. OBSERVER OR PUB/SUB PATTERN. var pubsub = {}; (function(q) { var topics = {}, subUid = -1; q.publish = function( topic, args ) { if ( !topics[topic] ) { return false; } var subscribers = topics[topic], len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func(topic, args);} return this; }; q.subscribe = function( topic, func ) { if (!topics[topic]) { topics[topic] = []; } var token = (++subUid).toString(); topics[topic].push({ token: token, func: func }); return token; }; }( pubsub ));
  • 16. COMMAND PATTERN 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. (function(){ var CarManager = { buyVehicle: function( model, id ){ return 'You have purchased Item ' + id + ', a ' + model; }}; })(); CarManager.execute = function (name) { return CarManager[name] && CarManager[name].apply (CarManager, [].slice.call(arguments, 1)); }; CarManager.execute("buyVehicle", "Ford Escort", "34232");
  • 17. MV* PATTERNS • Software Design pattern or Architecture design pattern?. • Coined by Trygve Reenskaug during his time working on Smalltalk-80 (1979) where it was initially called Model-View- Controller-Editor. • Variations: • MVC. Model-View-Controller. Spine.js / Backbone.js (MVR) • MVP. Model-View-Presenter. Backbone.js • MVVM. Model-View-ViewModel. Knockout.js / Knockback.js • It has been structuring desktop and server-side applications, but it's only been in recent years that come to being applied to JavaScript. • http://addyosmani.github.com/todomvc/
  • 18. BACKBONE.JS MVC, MVP OR MVR? • Flexible framework to build Javascript web applications. • Backbone.js doesn’t fit in any specific pattern. • There is no controller in Backbone. Views and Routers instead. • Backbone’s Architecture. • Model. Extend from Model or Collection. var Todo = Backbone.Model.extend({ defaults: { content: "empty todo...", done: false }, // Ensure that each todo created has `content`. initialize: function() { if (!this.get("content")) { this.set({"content": this.defaults.content}); } } });
  • 19. BACKBONE.JS COLLECTIONS • Model. Extend from Collection. var User = Backbone.Collection.extend({ model: User, url: 'https://api.twitter.com/1/user/show.json?id=7&callback=?', parse: function(response) { //console.log('parsing user ...'); return response; } });
  • 20. BACKBONE.JS VIEW • View. It can see as a a View, a Presenter or even a Controller. var PageView = Backbone.View.extend({ el: $('body'), events: { 'click button#add': 'doSearch' }, initialize: function() { this.template = _.template('<li><%= name %></li>'); _.bindAll(this, 'render', 'addItem'); this.('reset', function(collection) { _this.$('#tweets').empty(); collection.each(function(tweet) { _this.addItem(tweet); }); }); this.render(); }, …
  • 21. BACKBONE.JS VIEW CONT. … doSearch: function() { var subject = $('#search').val() || 'Node.js'; this.tweets.url = 'http://search.twitter.com/ search.json?q=’ + subject + '&rpp=8&callback=?'; this.tweets.fetch(); }, render: function() { var html = template({ img: item.get('profile_image_url') , user: item.get('from_user_name'), text: item.get('text') }); $('#tweets', this.el).append(html); return this; } }); You also use templating within the View layer. (Mustache.js, Jquery.tmpl, ….).
  • 22. BACKBONE.JS ROUTER • Router. It may be seen as a pseudo-controller. var myRouter = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/users "search/:query/p:page": "search" // #search/users/p7 }, help: function() { ... }, search: function(query, page) { ... } });
  • 23. SPINE.JS. MVC LIBRARY. • Controllers are considered the glue between the Model and the View. var PhotosController = Spine.Controller.sub({ init: function(){ this.item.bind("update", this.proxy(this.render)); this.item.bind("destroy", this.proxy(this.remove)); }, render: function(){ this.replace($("#photoTemplate").tmpl(this.item)); return this; }, remove: function(){ this.el.remove(); this.release(); } });
  • 24. KNOCKOUT.JS MVVM • Defined in 2005 by John Grossman for use with Windows Presentation Foundation (WPF) and Silverlight • More clearly separate the development of user- interfaces (UI) from that of the business logic and behavior in an application. • Make use of declarative data bindings to allow a separation of work on Views from other layers. It provides data-binding from the Model directly from the View • Based on Model View PresentationModel. Martin Fowler wrote an article on PresentationModels back in 2004
  • 25. KNOCKOUT.JS MVVM • Model. It uses the Observable property that can notify subscribers about changes and automatically detect dependencies • View. A KnockoutJS View is simply a HTML document with declarative bindings to link it to the ViewModel • ViewModel. The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.
  • 26. KNOCKOUT.JS VIEWMODEL function AppViewModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington"); this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); this.capitalizeLastName = function() { var currentVal = this.lastName(); this.lastName(currentVal.toUpperCase()); }; } // Activates knockout.js ko.applyBindings(new AppViewModel());
  • 27. KNOCKOUT.JS VIEW • Plain HTML <p>First name: <strong data-bind="text: firstName"></strong></p> <p>Last name: <strong data-bind="text: lastName"></strong></p> <p>First name: <input data-bind="value: firstName" /></p> <p>Last name: <input data-bind="value: lastName" /></p> <p>Full name: <strong data-bind="text: fullName"></strong></p> <button data-bind="click: capitalizeLastName">Go caps</button>

Notas del editor

  1. Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern. Intent: A description of the goal behind the pattern and the reason for using it. Also Known As: Other names for the pattern. Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used. Applicability: Situations in which this pattern is usable; the context for the pattern. Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose. Participants: A listing of the classes and objects used in the pattern and their roles in the design. Collaboration: A description of how classes and objects used in the pattern interact with each other. Consequences: A description of the results, side effects, and trade offs caused by using the pattern. Implementation: A description of an implementation of the pattern; the solution part of the pattern. Sample Code: An illustration of how the pattern can be used in a programming language. Known Uses: Examples of real usages of the pattern. Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.
  2. Object literal. var apple = { type: "macintosh", color: "red", getInfo: function () { return this.color + ' ' + this.type + ' apple'; } }
  3. Implementation. Illustrations. Examples. Co-requisites. Relations. Known usage. Discussions.
  4. Implementation. Illustrations. Examples. Co-requisites. Relations. Known usage. Discussions.
  5. Implementation. Illustrations. Examples. Co-requisites. Relations. Known usage. Discussions.
  6. 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).