SlideShare a Scribd company logo
JavaScript Modules
by Ivan Sirosh
JavaScript module pattern:
How to create it and why?
Approach to building large
applications
Module pattern requires understanding
modules as a system
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="/public/css/main.css">
</head>
<body>
<div id="content">
</div>
<script src="/public/js/libs/lib1.js"></script>
<script src="/public/js/libs/lib2.js"></script>
<script src="/public/js/libs/lib3.js"></script>
<script src="/module1.js"></script>
<script src="/module2.js"></script>
<script src="/app.js"></script>
</body>
</html>
This is how it’s usually done
var Module = {
a: 1,
b: function() {
//do something
}
};
Correct ****** pattern
(function () {
var a = 1;
function b(){
//do something
}
}());
Import of global variables
(function ($, YUI) {
$.each([1,2,3,4,5], function(){
//do something
});
var Y = YUI();
Y.use('node', function(Y){
//do something
});
}(jQuery, YUI));
Import of local variables
(function(awesome) {
var a;
awesome.splash(function() {
a = 1;
});
waterPool.set("new", function() {
return a;
});
} (waterPool.get("awesome")));
Export of the module
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// do something
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// do something
};
return my;
}());
Module extension if the module
doesn't exist
var MODULE = (function (my) {
my.anotherMethod = function () {
// do something
};
return my;
}(MODULE || {}));
We’re done here*
* almost done
Let's look at 3 types of solutions
The bad one
pure JS
var _modules = [];
_modules[0] = function(p){
//do something
};
_modules[1] = [];
_modules[1][0] = 1;
_modules[0](_modules[1][0]);
The ugly one –
Why reinvent the wheel?
pure JS
(function () {
var $ = this.jQuery;
this.myExample = function () {};
}());
The good one
AMD api
define(['jquery'] , function () {
return jQuery;
});
require(['jquery'] , function ($) {
console.log($.now());
});
Require JS
RequireJS is a JavaScript file and module loader. It is
optimized for in-browser use, but it can be used in other
JavaScript environments, like Rhino and Node. Using a
modular script loader like RequireJS will improve the speed
and quality of your code.
IE 6+ .......... compatible ✔
Firefox 2+ ..... compatible ✔
Safari 3.2+ .... compatible ✔
Chrome 3+ ...... compatible ✔
Opera 10+ ...... compatible ✔
http://requirejs.org
Almond JS
A replacement AMD loader for RequireJS. It is a smaller "shim"
loader, providing the minimal AMD API footprint that includes
loader plugin support.
What is supported:
• dependencies with relative IDs.
• define('id', {}) definitions.
• define(), require() and requirejs() calls.
https://github.com/jrburke/almond
AMD
The Asynchronous Module Definition
https://github.com/amdjs/amdjs-api/wiki/AMD
define(id, dependencies, factory);
require(dependencies, callback);
define
define('a-module', function () {
return 'a-module';
});
define('b-module', function () {
return 'b-module';
});
define('c-module', ['a-module', 'b-module'] function (a, b) {
return a + ' ' + b + ' ' + 'c-module';
});
require
require(['c-module'], function (c_module) {
if(c_module){
console.log(c_module)
}
});
a-module b-module c-module
define("alpha", ["require", "exports", "beta"], function(require, exports, beta) {
exports.verb = function() {
return beta.verb();
//Or:
return require("beta").verb();
}
});
define(["alpha"], function(alpha) {
return {
verb: function() {
return alpha.verb() + 2;
}
};
});
define({
add: function(x, y) {
return x + y;
}
});
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('my-awesome-module', [], factory);
} else {
root.MyAwesomeModule = factory();
}
}(this, function() {
var MyAwesomeModule = function() {};
return new MyAwesomeModule();
}));
If AMD JS isn't implemented,
modules can look as follows
jQuery example done already in the
new version which support AMD
(function(global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = global.document ? factory(global, true) : function(w) {
if (!w.document) {
throw new Error("jQuery requires a window with a document");
}
return factory(w);
};
} else {
factory(global);
}
}(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
var jQuery;
/*-----------------------------------*/
/* ...
/* extend jQuery oject
/* ...
/*-----------------------------------*/
return jQuery;
}));
Don't reinvent the wheel – just use it smartly ;)
JS Modules
Ad

More Related Content

What's hot (20)

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
Stéphane Bégaudeau
 
Require.JS
Require.JSRequire.JS
Require.JS
Ivano Malavolta
 
Requirejs
RequirejsRequirejs
Requirejs
sioked
 
React 소개 및 구현방법 Demo
React 소개 및 구현방법 DemoReact 소개 및 구현방법 Demo
React 소개 및 구현방법 Demo
Daesung Kim
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Iván Fernández Perea
 
Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General Overview
Visual Engineering
 
Angularjs architecture
Angularjs architectureAngularjs architecture
Angularjs architecture
Michael He
 
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
Stéphane Bégaudeau
 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
Kim Hunmin
 
Require js
Require jsRequire js
Require js
Nirbhay Kundan
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 
Asp.net MVC - Course 2
Asp.net MVC - Course 2Asp.net MVC - Course 2
Asp.net MVC - Course 2
erdemergin
 
An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications
Rohan Chandane
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Step by Step - AngularJS
Step by Step - AngularJSStep by Step - AngularJS
Step by Step - AngularJS
Infragistics
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
Mariusz Nowak
 
Develop plugin for Mozilla Firefox and structure a JS-based application
Develop plugin for Mozilla Firefox and structure a JS-based applicationDevelop plugin for Mozilla Firefox and structure a JS-based application
Develop plugin for Mozilla Firefox and structure a JS-based application
Afshin Mehrabani
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
Visual Engineering
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
Ivano Malavolta
 
Jsp lecture
Jsp lectureJsp lecture
Jsp lecture
Tata Consultancy Services
 
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
Stéphane Bégaudeau
 
Requirejs
RequirejsRequirejs
Requirejs
sioked
 
React 소개 및 구현방법 Demo
React 소개 및 구현방법 DemoReact 소개 및 구현방법 Demo
React 소개 및 구현방법 Demo
Daesung Kim
 
Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General Overview
Visual Engineering
 
Angularjs architecture
Angularjs architectureAngularjs architecture
Angularjs architecture
Michael He
 
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
Stéphane Bégaudeau
 
Dom selecting & jQuery
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
Kim Hunmin
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
IMC Institute
 
Asp.net MVC - Course 2
Asp.net MVC - Course 2Asp.net MVC - Course 2
Asp.net MVC - Course 2
erdemergin
 
An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications
Rohan Chandane
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Step by Step - AngularJS
Step by Step - AngularJSStep by Step - AngularJS
Step by Step - AngularJS
Infragistics
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
Mariusz Nowak
 
Develop plugin for Mozilla Firefox and structure a JS-based application
Develop plugin for Mozilla Firefox and structure a JS-based applicationDevelop plugin for Mozilla Firefox and structure a JS-based application
Develop plugin for Mozilla Firefox and structure a JS-based application
Afshin Mehrabani
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
Visual Engineering
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
Ivano Malavolta
 

Similar to JavaScript Modules in Practice (20)

Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
Brian Cavalier
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources framework
marcplmer
 
Modules and EmbedJS
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJS
Jens Arps
 
Zend
ZendZend
Zend
Mohamed Ramadan
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript Conference
Bo-Yi Wu
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
Gabriel Walt
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
Gordon Forsythe
 
Zend Framework Quick Start Walkthrough
Zend Framework Quick Start WalkthroughZend Framework Quick Start Walkthrough
Zend Framework Quick Start Walkthrough
Bradley Holt
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
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
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
Bo-Yi Wu
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
James Titcumb
 
Web-Performance
Web-PerformanceWeb-Performance
Web-Performance
Walter Ebert
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
Ioan Eugen Stan
 
Single Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle StorySingle Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle Story
Kon Soulianidis
 
Social Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedSocial Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes Demystified
Claudio Procida
 
Webpack
Webpack Webpack
Webpack
Sofian Hadiwijaya
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources framework
marcplmer
 
Modules and EmbedJS
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJS
Jens Arps
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript Conference
Bo-Yi Wu
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
Gabriel Walt
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
Gordon Forsythe
 
Zend Framework Quick Start Walkthrough
Zend Framework Quick Start WalkthroughZend Framework Quick Start Walkthrough
Zend Framework Quick Start Walkthrough
Bradley Holt
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
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
 
Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
Bo-Yi Wu
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
James Titcumb
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
Ioan Eugen Stan
 
Single Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle StorySingle Page JavaScript WebApps... A Gradle Story
Single Page JavaScript WebApps... A Gradle Story
Kon Soulianidis
 
Social Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedSocial Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes Demystified
Claudio Procida
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Ad

Recently uploaded (20)

WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Ad

JavaScript Modules in Practice

  • 2. JavaScript module pattern: How to create it and why?
  • 3. Approach to building large applications
  • 4. Module pattern requires understanding modules as a system <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="/public/css/main.css"> </head> <body> <div id="content"> </div> <script src="/public/js/libs/lib1.js"></script> <script src="/public/js/libs/lib2.js"></script> <script src="/public/js/libs/lib3.js"></script> <script src="/module1.js"></script> <script src="/module2.js"></script> <script src="/app.js"></script> </body> </html>
  • 5. This is how it’s usually done var Module = { a: 1, b: function() { //do something } };
  • 6. Correct ****** pattern (function () { var a = 1; function b(){ //do something } }());
  • 7. Import of global variables (function ($, YUI) { $.each([1,2,3,4,5], function(){ //do something }); var Y = YUI(); Y.use('node', function(Y){ //do something }); }(jQuery, YUI));
  • 8. Import of local variables (function(awesome) { var a; awesome.splash(function() { a = 1; }); waterPool.set("new", function() { return a; }); } (waterPool.get("awesome")));
  • 9. Export of the module var MODULE = (function () { var my = {}, privateVariable = 1; function privateMethod() { // do something } my.moduleProperty = 1; my.moduleMethod = function () { // do something }; return my; }());
  • 10. Module extension if the module doesn't exist var MODULE = (function (my) { my.anotherMethod = function () { // do something }; return my; }(MODULE || {}));
  • 11. We’re done here* * almost done
  • 12. Let's look at 3 types of solutions
  • 13. The bad one pure JS var _modules = []; _modules[0] = function(p){ //do something }; _modules[1] = []; _modules[1][0] = 1; _modules[0](_modules[1][0]);
  • 14. The ugly one – Why reinvent the wheel? pure JS (function () { var $ = this.jQuery; this.myExample = function () {}; }());
  • 15. The good one AMD api define(['jquery'] , function () { return jQuery; }); require(['jquery'] , function ($) { console.log($.now()); });
  • 16. Require JS RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code. IE 6+ .......... compatible ✔ Firefox 2+ ..... compatible ✔ Safari 3.2+ .... compatible ✔ Chrome 3+ ...... compatible ✔ Opera 10+ ...... compatible ✔ http://requirejs.org
  • 17. Almond JS A replacement AMD loader for RequireJS. It is a smaller "shim" loader, providing the minimal AMD API footprint that includes loader plugin support. What is supported: • dependencies with relative IDs. • define('id', {}) definitions. • define(), require() and requirejs() calls. https://github.com/jrburke/almond
  • 18. AMD The Asynchronous Module Definition https://github.com/amdjs/amdjs-api/wiki/AMD define(id, dependencies, factory); require(dependencies, callback);
  • 19. define define('a-module', function () { return 'a-module'; }); define('b-module', function () { return 'b-module'; }); define('c-module', ['a-module', 'b-module'] function (a, b) { return a + ' ' + b + ' ' + 'c-module'; });
  • 20. require require(['c-module'], function (c_module) { if(c_module){ console.log(c_module) } }); a-module b-module c-module
  • 21. define("alpha", ["require", "exports", "beta"], function(require, exports, beta) { exports.verb = function() { return beta.verb(); //Or: return require("beta").verb(); } });
  • 22. define(["alpha"], function(alpha) { return { verb: function() { return alpha.verb() + 2; } }; }); define({ add: function(x, y) { return x + y; } });
  • 23. (function(root, factory) { if (typeof define === 'function' && define.amd) { define('my-awesome-module', [], factory); } else { root.MyAwesomeModule = factory(); } }(this, function() { var MyAwesomeModule = function() {}; return new MyAwesomeModule(); })); If AMD JS isn't implemented, modules can look as follows
  • 24. jQuery example done already in the new version which support AMD (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") { module.exports = global.document ? factory(global, true) : function(w) { if (!w.document) { throw new Error("jQuery requires a window with a document"); } return factory(w); }; } else { factory(global); } }(typeof window !== "undefined" ? window : this, function(window, noGlobal) { var jQuery; /*-----------------------------------*/ /* ... /* extend jQuery oject /* ... /*-----------------------------------*/ return jQuery; }));
  • 25. Don't reinvent the wheel – just use it smartly ;) JS Modules