SlideShare une entreprise Scribd logo
1  sur  56
Télécharger pour lire hors ligne
Javascript Design Patterns.
AMD & commonJS.
RequireJS
Marc Torrent Vernetta
Javascript Design Patterns
A reusable solution that can be applied to commonly occurring problems
in software design -in our case- in writing JavaScript Web application.
What is a Pattern?
Templates for how we solve problems - ones which can be used in quite
a few different situations situations
Addy Osmani
Three Main Benefits
1. Proven Solutions
2. Easily Reused
3. Expressive
NOT EXACT SOLUTIONS SUPPORT DEVELOPERS
A Good Pattern
1. Solves a particular problem
2. Not an obvious solution
3. A proven described concept
4. Describe a relationship
Display some recurring phenomenon:
❖ Fitness of purpose
❖ Usefulness
❖ Applicability
Antipatterns
1. Polluting global namespace
2. Strings to setTimeout and setInterval + eval()
3. Modify the Object prototype (very bad!!)
4. Javascript in an inline form
5. Use of document.write
Knowledge for anti-patterns is critical for success !!!!
Antipatterns
1. Polluting global namespace
2. Strings to setTimeout and setInterval + eval()
3. Modify the Object prototype (very bad!!)
4. Javascript in an inline form
5. Use of document.write
Knowledge for anti-patterns is critical for success !!!!
Design Pattern Types
➢ Creational
○ Factory Pattern
○ Constructor Pattern
○ Singleton Pattern
○ Prototype Pattern
➢ Structural
○ Module Pattern
○ Adapter Pattern
○ Decorator Pattern
○ Façade Pattern
○ Mixin Pattern
○ Flyweight Pattern
➢ Behavioral
○ Mediator Pattern
○ Observer Pattern
- Classes
- Objects
Creational Patterns
Constructor Pattern
Constructor Pattern - Prototype
Prototype Pattern
Sub-Classing
Mixin Pattern
Structural Patterns
Module Pattern - Object Literal
Module Pattern - IIFE
Module Pattern - Revealing
Behavioral Patterns
Observer Pattern - I
SUBJECT STATE
OBSERVERS LIST
OBSERVER OBSERVER OBSERVER OBSERVER OBSERVER
N O T I F Y
CONCRETE
SUBJECT
CONCRETE
OBSERVER
UPDATEUPDATEUPDATEUPDATEUPDATE
Observer Pattern - II
Observer Pattern - III
Observer Pattern - IV
Observer Pattern - V
Observer Pattern - VI
Observer Pattern - VII
Publish/Subscribe Pattern - I
PUBLISHER
(SUBJECT)
SUBSCRIBER
EVENT AGGREGATOR
SUBSCRIBER SUBSCRIBER
Publish/Subscribe Pattern II
Publish/Subscribe Pattern III
Publish/Subscribe Pattern IV
Mediator Pattern - I
SUBJECT
SUBSCRIBER
EVENT AGGREGATOR
SUBSCRIBER SUBSCRIBER
MEDIATOR
Mediator Pattern - II
Mediator Pattern - III
Mediator Pattern - IV
Mediator Pattern - V
Modern Modular JavaScript Design
Patterns
Module A Module B Module C Module N…...
Application
- Modular Application
- Loosely Coupled
- Dependency Control
- Script Loader
➢ BROWSER:
- Asynchronous
Module Definition
(AMD)
- requireJS
➢ SERVER:
- commonJS
Dependency Control
AMD Modules
➢ Defining modules with dependencies to other modules.
➢ The module and dependencies can be asynchronously
loaded.
➢ Both modules are asynchronous and highly flexible by
nature
➢ Removes the tight coupling between code and module
identity
AMD Modules Advantages
● Provides a clear proposal for how to approach defining flexible
modules.
● Significantly cleaner than the present global namespace and <script>
tag solutions many of us rely on. There's a clean way to declare
stand-alone modules and dependencies they may have.
● Module definitions are encapsulated, helping us to avoid pollution of
the global namespace.
● Most AMD loaders support loading modules in the browser without
a build process.
● Provides a "transport" approach for including multiple modules in a
single file.
● It's possible to lazy load scripts if this is needed.
AMD Modules - define vs require
define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the
module or object*/
);
require(
[dependencies] /*required*/,
complete function /*function for instantiating the
dependecies*/
);
AMD Modules - define vs require
define([“url_to_anonymous_module”, “named_module_id”],
function(ModuleA, ModuleB) {
function doCoolStuff(a) {
ModuleA.cool(a, ModuleB.getCool());
}
return {
cool: doCoolStuff
};
}
);
require([“myModule”], function(moduleC) {
var superCool = “super cool”;
moduleC.cool(superCool);
});
requireJS
➢ Library for working with AMD modules. Asynchronous script loader and
dependency manager.
➢ Easy naming definition with a json configuration. Prepare non AMD
modules for other AMD modules as its dependency management stays
untouched.
➢ Optimization tool for bundling modules in one or many optimized, uglified
and minimized module.
➢ With plugin extension for loading non JS scripts, like CSS, JSON, JSONP,
etc…
➢ commonJS wrapper for styling AMD module loading with commonJS
syntax and reducing verbosity.
requireJS and AMD
require([dependencies], function(depA, depB, ...){});
requirejs([dependencies], function(depA, depB, ...){});
define() function and module definition remains exactly the same
requirejs.config({
baseUrl: ‘path_to_where_scripts_are’,
paths: {
name_of_a_module: ‘relative_path_of_the_module’,
other_module_name: ‘relative_path_of_other_module’
},
shim: {
name_of_a_module: {
exports: ‘Foo’,
},
other_module_name: [“name_of_a_module”]
}
});
requireJS and HTML
<html>
<head></head>
<body>
<script data-main="js/app.js"
src="js/require.js"></script>
<script type=”text/javascript”>
requirejs([“app”], function(app) {
app.start();
});
</script>
</body>
</html>
commonJS modules
➢ Reusable piece of JavaScript which exports specific objects
made available to any dependent code.
➢ Unlike AMD, there are typically no function wrappers
around such modules.
➢ Two primary parts: a free variable named exports which
contains the objects a module wishes to make available to
other modules and a require function that modules can use
to import the exports of other modules
➢ Only able to define objects which can be tedious to work
with if we're trying to obtain constructors out of them
➢ Useful for Server side because it can use io, fs, system, etc..
commonJS in depth
var libA = require(‘package/libA’),
libB = require(‘package/libB’);
function foo(){
libA.log( ‘hello world!’ );
}
exports.foo = foo;
exports.bar = function bar() {
libB.myFunc();
};
var foobar = require(‘foobar’);
foobar.foo();
foobar.bar();
requireJS with commonJS style
define(function(require) {
var moduleA = require(‘moduleA’),
moduleB = require(‘moduleB’);
function doCoolStuff(a) {
moduleA.cool(a, moduleB.getCool());
}
return {
cool: doCoolStuff
};
}
);
Library App with RequireJS & AMD
Thanks for your attention!
Leave your questions on the comments section
Workshop 2: JavaScript Design Patterns

Contenu connexe

Tendances

Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 

Tendances (20)

AngularJS with RequireJS
AngularJS with RequireJSAngularJS with RequireJS
AngularJS with RequireJS
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
AngularJS introduction
AngularJS introductionAngularJS introduction
AngularJS introduction
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Angular js
Angular jsAngular js
Angular js
 
Managing JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSManaging JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJS
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
5 angularjs features
5 angularjs features5 angularjs features
5 angularjs features
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
 
SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 

Similaire à Workshop 2: JavaScript Design Patterns

Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
Spike Brehm
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
Nicole Gomez
 
JavaScript & Enterprise BED-Con 2014 Berlin German
JavaScript & Enterprise BED-Con 2014 Berlin GermanJavaScript & Enterprise BED-Con 2014 Berlin German
JavaScript & Enterprise BED-Con 2014 Berlin German
Adam Boczek
 
Modular JavaScript in an OSGi World - S Mak
Modular JavaScript in an OSGi World - S MakModular JavaScript in an OSGi World - S Mak
Modular JavaScript in an OSGi World - S Mak
mfrancis
 
Backend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In BanglaBackend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In Bangla
Stack Learner
 

Similaire à Workshop 2: JavaScript Design Patterns (20)

Modules and EmbedJS
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJS
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
JavaScript Module Loaders
JavaScript Module LoadersJavaScript Module Loaders
JavaScript Module Loaders
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
 
Introduction to C3.net Architecture unit
Introduction to C3.net Architecture unitIntroduction to C3.net Architecture unit
Introduction to C3.net Architecture unit
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
RequireJS
RequireJSRequireJS
RequireJS
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
Javascript from beginning to modern
Javascript from beginning to modernJavascript from beginning to modern
Javascript from beginning to modern
 
Introduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEBIntroduction to mean and mern || Event by DSC UNIDEB
Introduction to mean and mern || Event by DSC UNIDEB
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
7 Redux challenges
7 Redux challenges7 Redux challenges
7 Redux challenges
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
JavaScript & Enterprise BED-Con 2014 Berlin German
JavaScript & Enterprise BED-Con 2014 Berlin GermanJavaScript & Enterprise BED-Con 2014 Berlin German
JavaScript & Enterprise BED-Con 2014 Berlin German
 
Modular JavaScript in an OSGi World - S Mak
Modular JavaScript in an OSGi World - S MakModular JavaScript in an OSGi World - S Mak
Modular JavaScript in an OSGi World - S Mak
 
Backend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In BanglaBackend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In Bangla
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.org
 

Plus de Visual Engineering

Plus de Visual Engineering (20)

Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Workshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototyping
 

Dernier

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Dernier (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
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
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Workshop 2: JavaScript Design Patterns

  • 1. Javascript Design Patterns. AMD & commonJS. RequireJS Marc Torrent Vernetta
  • 3. A reusable solution that can be applied to commonly occurring problems in software design -in our case- in writing JavaScript Web application. What is a Pattern? Templates for how we solve problems - ones which can be used in quite a few different situations situations Addy Osmani
  • 4. Three Main Benefits 1. Proven Solutions 2. Easily Reused 3. Expressive NOT EXACT SOLUTIONS SUPPORT DEVELOPERS
  • 5. A Good Pattern 1. Solves a particular problem 2. Not an obvious solution 3. A proven described concept 4. Describe a relationship Display some recurring phenomenon: ❖ Fitness of purpose ❖ Usefulness ❖ Applicability
  • 6. Antipatterns 1. Polluting global namespace 2. Strings to setTimeout and setInterval + eval() 3. Modify the Object prototype (very bad!!) 4. Javascript in an inline form 5. Use of document.write Knowledge for anti-patterns is critical for success !!!!
  • 7. Antipatterns 1. Polluting global namespace 2. Strings to setTimeout and setInterval + eval() 3. Modify the Object prototype (very bad!!) 4. Javascript in an inline form 5. Use of document.write Knowledge for anti-patterns is critical for success !!!!
  • 8. Design Pattern Types ➢ Creational ○ Factory Pattern ○ Constructor Pattern ○ Singleton Pattern ○ Prototype Pattern ➢ Structural ○ Module Pattern ○ Adapter Pattern ○ Decorator Pattern ○ Façade Pattern ○ Mixin Pattern ○ Flyweight Pattern ➢ Behavioral ○ Mediator Pattern ○ Observer Pattern - Classes - Objects
  • 16. Module Pattern - Object Literal
  • 18. Module Pattern - Revealing
  • 20. Observer Pattern - I SUBJECT STATE OBSERVERS LIST OBSERVER OBSERVER OBSERVER OBSERVER OBSERVER N O T I F Y CONCRETE SUBJECT CONCRETE OBSERVER UPDATEUPDATEUPDATEUPDATEUPDATE
  • 27. Publish/Subscribe Pattern - I PUBLISHER (SUBJECT) SUBSCRIBER EVENT AGGREGATOR SUBSCRIBER SUBSCRIBER
  • 31.
  • 32. Mediator Pattern - I SUBJECT SUBSCRIBER EVENT AGGREGATOR SUBSCRIBER SUBSCRIBER MEDIATOR
  • 37. Modern Modular JavaScript Design Patterns
  • 38. Module A Module B Module C Module N…... Application - Modular Application - Loosely Coupled - Dependency Control - Script Loader ➢ BROWSER: - Asynchronous Module Definition (AMD) - requireJS ➢ SERVER: - commonJS Dependency Control
  • 39. AMD Modules ➢ Defining modules with dependencies to other modules. ➢ The module and dependencies can be asynchronously loaded. ➢ Both modules are asynchronous and highly flexible by nature ➢ Removes the tight coupling between code and module identity
  • 40. AMD Modules Advantages ● Provides a clear proposal for how to approach defining flexible modules. ● Significantly cleaner than the present global namespace and <script> tag solutions many of us rely on. There's a clean way to declare stand-alone modules and dependencies they may have. ● Module definitions are encapsulated, helping us to avoid pollution of the global namespace. ● Most AMD loaders support loading modules in the browser without a build process. ● Provides a "transport" approach for including multiple modules in a single file. ● It's possible to lazy load scripts if this is needed.
  • 41. AMD Modules - define vs require define( module_id /*optional*/, [dependencies] /*optional*/, definition function /*function for instantiating the module or object*/ ); require( [dependencies] /*required*/, complete function /*function for instantiating the dependecies*/ );
  • 42. AMD Modules - define vs require define([“url_to_anonymous_module”, “named_module_id”], function(ModuleA, ModuleB) { function doCoolStuff(a) { ModuleA.cool(a, ModuleB.getCool()); } return { cool: doCoolStuff }; } ); require([“myModule”], function(moduleC) { var superCool = “super cool”; moduleC.cool(superCool); });
  • 43. requireJS ➢ Library for working with AMD modules. Asynchronous script loader and dependency manager. ➢ Easy naming definition with a json configuration. Prepare non AMD modules for other AMD modules as its dependency management stays untouched. ➢ Optimization tool for bundling modules in one or many optimized, uglified and minimized module. ➢ With plugin extension for loading non JS scripts, like CSS, JSON, JSONP, etc… ➢ commonJS wrapper for styling AMD module loading with commonJS syntax and reducing verbosity.
  • 44. requireJS and AMD require([dependencies], function(depA, depB, ...){}); requirejs([dependencies], function(depA, depB, ...){}); define() function and module definition remains exactly the same requirejs.config({ baseUrl: ‘path_to_where_scripts_are’, paths: { name_of_a_module: ‘relative_path_of_the_module’, other_module_name: ‘relative_path_of_other_module’ }, shim: { name_of_a_module: { exports: ‘Foo’, }, other_module_name: [“name_of_a_module”] } });
  • 45. requireJS and HTML <html> <head></head> <body> <script data-main="js/app.js" src="js/require.js"></script> <script type=”text/javascript”> requirejs([“app”], function(app) { app.start(); }); </script> </body> </html>
  • 46. commonJS modules ➢ Reusable piece of JavaScript which exports specific objects made available to any dependent code. ➢ Unlike AMD, there are typically no function wrappers around such modules. ➢ Two primary parts: a free variable named exports which contains the objects a module wishes to make available to other modules and a require function that modules can use to import the exports of other modules ➢ Only able to define objects which can be tedious to work with if we're trying to obtain constructors out of them ➢ Useful for Server side because it can use io, fs, system, etc..
  • 47. commonJS in depth var libA = require(‘package/libA’), libB = require(‘package/libB’); function foo(){ libA.log( ‘hello world!’ ); } exports.foo = foo; exports.bar = function bar() { libB.myFunc(); }; var foobar = require(‘foobar’); foobar.foo(); foobar.bar();
  • 48. requireJS with commonJS style define(function(require) { var moduleA = require(‘moduleA’), moduleB = require(‘moduleB’); function doCoolStuff(a) { moduleA.cool(a, moduleB.getCool()); } return { cool: doCoolStuff }; } );
  • 49. Library App with RequireJS & AMD
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. Thanks for your attention! Leave your questions on the comments section