SlideShare a Scribd company logo
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
Workshop 2: JavaScript Design Patterns
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
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Thanks for your attention!
Leave your questions on the comments section
Workshop 2: JavaScript Design Patterns

More Related Content

What's hot (20)

PDF
AngularJS with RequireJS
Johannes Weber
 
PDF
AngularJS application architecture
Gabriele Falace
 
PDF
Dependency Injection @ AngularJS
Ran Mizrahi
 
PDF
AngularJS introduction
Tania Gonzales
 
PDF
AngularJS 101 - Everything you need to know to get started
Stéphane Bégaudeau
 
PPTX
Introduction to Angularjs
Manish Shekhawat
 
PPTX
Angular js
Behind D Walls
 
PPT
Managing JavaScript Dependencies With RequireJS
Den Odell
 
PDF
AngularJS Basics
Ravi Mone
 
PDF
How to build to do app using vue composition api and vuex 4 with typescript
Katy Slemon
 
PPTX
5 angularjs features
Alexey (Mr_Mig) Migutsky
 
PPTX
Why angular js Framework
Sakthi Bro
 
PDF
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
e-Legion
 
PDF
AngularJS - What is it & Why is it awesome ? (with demos)
Gary Arora
 
PDF
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 
PDF
Modern Web Application Development Workflow - EclipseCon Europe 2014
Stéphane Bégaudeau
 
PDF
SpringMVC
Akio Katayama
 
PDF
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
PDF
AngularJS Best Practices
Betclic Everest Group Tech Team
 
PPTX
Angular 2.0 Routing and Navigation
Eyal Vardi
 
AngularJS with RequireJS
Johannes Weber
 
AngularJS application architecture
Gabriele Falace
 
Dependency Injection @ AngularJS
Ran Mizrahi
 
AngularJS introduction
Tania Gonzales
 
AngularJS 101 - Everything you need to know to get started
Stéphane Bégaudeau
 
Introduction to Angularjs
Manish Shekhawat
 
Angular js
Behind D Walls
 
Managing JavaScript Dependencies With RequireJS
Den Odell
 
AngularJS Basics
Ravi Mone
 
How to build to do app using vue composition api and vuex 4 with typescript
Katy Slemon
 
5 angularjs features
Alexey (Mr_Mig) Migutsky
 
Why angular js Framework
Sakthi Bro
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
e-Legion
 
AngularJS - What is it & Why is it awesome ? (with demos)
Gary Arora
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Stéphane Bégaudeau
 
SpringMVC
Akio Katayama
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
AngularJS Best Practices
Betclic Everest Group Tech Team
 
Angular 2.0 Routing and Navigation
Eyal Vardi
 

Similar to Workshop 2: JavaScript Design Patterns (20)

PDF
Advanced Node.JS Meetup
LINAGORA
 
PDF
Asynchronous Module Definition (AMD)
xMartin12
 
KEY
Modules and EmbedJS
Jens Arps
 
PDF
Introduction to JavaScript design patterns
Jeremy Duvall
 
PDF
"The JavaScript Design Patterns You have to Know" by Rashad Majali
Jordan Open Source Association
 
PDF
JavaScript Modules Done Right
Mariusz Nowak
 
PDF
Modular JavaScript
Andrew Eisenberg
 
PDF
Александр Белецкий "Архитектура Javascript приложений"
Agile Base Camp
 
PDF
Modular JavaScript
NLJUG
 
PDF
Scalable JavaScript Design Patterns
Addy Osmani
 
PDF
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
PDF
Require js training
Dr. Awase Khirni Syed
 
PDF
JavaScript Dependencies, Modules & Browserify
Johan Nilsson
 
PDF
Design patterns in javascript
Ayush Sharma
 
PDF
Javascript Design Patterns
Lilia Sfaxi
 
PPTX
Binary Studio Academy PRO. JS course. Lecture 1. UI Architecture.
Binary Studio
 
PDF
Develop plugin for Mozilla Firefox and structure a JS-based application
Afshin Mehrabani
 
PDF
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 
PPSX
RequireJS
Tim Doherty
 
PDF
Module, AMD, RequireJS
偉格 高
 
Advanced Node.JS Meetup
LINAGORA
 
Asynchronous Module Definition (AMD)
xMartin12
 
Modules and EmbedJS
Jens Arps
 
Introduction to JavaScript design patterns
Jeremy Duvall
 
"The JavaScript Design Patterns You have to Know" by Rashad Majali
Jordan Open Source Association
 
JavaScript Modules Done Right
Mariusz Nowak
 
Modular JavaScript
Andrew Eisenberg
 
Александр Белецкий "Архитектура Javascript приложений"
Agile Base Camp
 
Modular JavaScript
NLJUG
 
Scalable JavaScript Design Patterns
Addy Osmani
 
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Require js training
Dr. Awase Khirni Syed
 
JavaScript Dependencies, Modules & Browserify
Johan Nilsson
 
Design patterns in javascript
Ayush Sharma
 
Javascript Design Patterns
Lilia Sfaxi
 
Binary Studio Academy PRO. JS course. Lecture 1. UI Architecture.
Binary Studio
 
Develop plugin for Mozilla Firefox and structure a JS-based application
Afshin Mehrabani
 
Unleashing the Power of Modern Javascript Development
Tarandeep Singh
 
RequireJS
Tim Doherty
 
Module, AMD, RequireJS
偉格 高
 
Ad

More from Visual Engineering (20)

PDF
Workshop iOS 4: Closures, generics & operators
Visual Engineering
 
PDF
Workshop iOS 3: Testing, protocolos y extensiones
Visual Engineering
 
PDF
Workshop iOS 2: Swift - Structures
Visual Engineering
 
PDF
Workhop iOS 1: Fundamentos de Swift
Visual Engineering
 
PDF
Workshop 26: React Native - The Native Side
Visual Engineering
 
PDF
Workshop 25: React Native - Components
Visual Engineering
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PDF
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
PDF
Workshop 22: React-Redux Middleware
Visual Engineering
 
PDF
Workshop 21: React Router
Visual Engineering
 
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
PDF
Workshop 19: ReactJS Introduction
Visual Engineering
 
PDF
Workshop 18: CSS Animations & cool effects
Visual Engineering
 
PDF
Workshop 17: EmberJS parte II
Visual Engineering
 
PDF
Workshop 15: Ionic framework
Visual Engineering
 
PDF
Workshop 14: AngularJS Parte III
Visual Engineering
 
PDF
Workshop 13: AngularJS Parte II
Visual Engineering
 
PDF
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
PDF
Workshop 12: AngularJS Parte I
Visual Engineering
 
PDF
Workshop 11: Trendy web designs & prototyping
Visual Engineering
 
Workshop iOS 4: Closures, generics & operators
Visual Engineering
 
Workshop iOS 3: Testing, protocolos y extensiones
Visual Engineering
 
Workshop iOS 2: Swift - Structures
Visual Engineering
 
Workhop iOS 1: Fundamentos de Swift
Visual Engineering
 
Workshop 26: React Native - The Native Side
Visual Engineering
 
Workshop 25: React Native - Components
Visual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
Workshop 22: React-Redux Middleware
Visual Engineering
 
Workshop 21: React Router
Visual Engineering
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Workshop 19: ReactJS Introduction
Visual Engineering
 
Workshop 18: CSS Animations & cool effects
Visual Engineering
 
Workshop 17: EmberJS parte II
Visual Engineering
 
Workshop 15: Ionic framework
Visual Engineering
 
Workshop 14: AngularJS Parte III
Visual Engineering
 
Workshop 13: AngularJS Parte II
Visual Engineering
 
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
Workshop 12: AngularJS Parte I
Visual Engineering
 
Workshop 11: Trendy web designs & prototyping
Visual Engineering
 
Ad

Recently uploaded (20)

PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Import Data Form Excel to Tally Services
Tally xperts
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 

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
  • 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
  • 55. Thanks for your attention! Leave your questions on the comments section