SlideShare una empresa de Scribd logo
1 de 65
Descargar para leer sin conexión
Module, AMD, RequireJS
      othree @ JSDC 2012
Object
Object Oriented
 Programming
Why OOP


• Maintainable & Scalable
• Gathering related variables & methods
Object from OOP

• Inheritance
• Polymorphism
• Encapsulation
Encapsulation


• A language mechanism for restricting
  access to some of the object's components.




         http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Why Encapsulation


• Protect variable from unwanted change
JavaScript is
Prototype-based
Private Data in
   JavaScript
Naming Convention
function Human(sgender) {
    //Private
    this._age = 1;
    this._gender = sgender || 'Male';

    //Public
    this.growUp = function () {
        this._age++;
    };
}
Accessible Anywhere


                _age




Human         _gender




               growUp
Privileged Method
function Human(sgender) {
    //Private
    var age = 1,
        gender = sgender || 'Male';

    //Privileged Method
    this.growUp = function () {
        age++;
    };
}




                                  http://javascript.crockford.com/private.html
Accessible Anywhere



Human


 age
                growUp

gender
Module Pattern
Module Pattern
function Human(sgender) {
    //Private
    var age = 1,
        gender = sgender || 'Male';

    //Public
    return {
        growUp: function () {
             age++;
        }
    };
}




                            http://yuiblog.com/blog/2007/06/12/module-pattern/
Accessible Anywhere
Human


 age



gender




         exports     growUp
Advantage


• Easy
• Keep private data safe
Disadvantage


• Hard to inherit
Large Application


• Lots of modules
• Complex dependency
Lots of Modules

• One file per module
• Lots of files:
 • Performance Issue
 • Async loading?
Complex Dependency


• Load modules by order
• Hard to know the order by head and hand
Solution?


• Not hard to solve
• But there is no standard API
CommonJS
CommonJS

• by Kevin Dangoor
• Volunteers and mailing list
• Unify server side JavaScript API
• Build JavaScript ecosystem
• Not an official organization
CommonJS APIs

• Binary
• Filesystem
• IO
• ...
• Modules
CommonJS Module

• Modules/1.0
 • NodeJS
• Modules/AsynchronousDefinition
 • AMD
AMD
Asynchronous Module
     Definition


   define(id?, dependencies?, factory);
Example
define(
    'account',
    ['service', 'pubsub'],
    function (service, pubsub) {
        //do something

         //export public APIs
         return {
             signin: function () { /* ... */ },
             signout: function () { /* ... */ },
             getName: function () { /* ... */ },
             setName: function () { /* ... */ }
         };
     }
);
Another Way
(function () {
    //10000 lines of code

    exports = {
        signin: function () { /* ... */ },
        signout: function () { /* ... */ }
    };

    define('account', function () {
        return exports;
    });
}());
In jQuery


if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
	    define( "jquery", [], function () { return jQuery; } );
}
RequireJS
RequireJS

• AMD Implementation by James Burke
• Async resource loader
• 1.0.8 now, 2.0 under development
Usage


<script data-main="main" src="require.js"></script>
main.js
require(["app"], function(app) {

      app.init();

});
app.js
define(["lib/account", "lib/session"],
    function (account, session) {
        //do something

         return {
             init: function () {
                  //init the application
             }
         };
     }
);
main.js




                                 app.js




           account.js                     session.js




crypt.js                xhr.js                     storage.js
Features

• AMD
• Path alias
• Circular dependency
• Plugins
Plugins

• order
• text
• wrap, use
• cs (CoffeeScript)
Advantages

• No pollution to global scope
• Everything is organized in module
• Compile CoffeeScript on the fly
• ...etc
Minefield

• Module load fail: hard to debug
 • Wrong path
 • Use require function
 • Plugin error, ex: CoffeeScript syntax error
Still Problems

• Lots of modules
• Lots of files
• Lots of requests
• Low performance
r.js
r.js

• Optimization tool
• Pack all modules into one file
• Minimize the JavaScript file
Usage


node r.js -o build.js
build.js
({
     appDir: "../",
     baseUrl: "scripts",
     dir: "../../appdirectory-build",
     modules: [
         {
             name: "main"
         }
     ]
})
main.js




                                 app.js




           account.js                     session.js




crypt.js                xhr.js                     storage.js
After Optimized


• require.js are large: 86kb
almond.js
almond.js


• Minimal AMD API implement
• Same author
Advantages


• Small: 9kb, 857 bytes minimized and gzipped
• Stable: no change since 0.0.3
Disadvantages

• No plugin support
• Not a resource downloader
• Lots of restriction
• Different optimize concept
Usage

node r.js -o baseUrl=.
     name=path/to/almond.js
     include=main
     out=main-built.js
     wrap=true
Tip


• You can use r.js to optimize
• And use almond.js to replace require.js
<script src="almond.js"></script>
<script src="main-optimized.js"></script>
References

•   http://www.yuiblog.com/blog/2007/06/12/module-pattern/

•   http://wiki.commonjs.org/wiki/Modules/1.1

•   http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition

•   https://github.com/amdjs/amdjs-api/wiki/AMD

•   http://requirejs.org/

•   https://github.com/jrburke/almond
Questions Time
Q


• I want to use Underscore and Backbone,
  but they don’t support RequireJS....
A

• Do nothing
• Use use/wrap plugin
• Use modified version
  https://github.com/jrburke
• Use another script tag to include them first
<script src="undersocre+backbone.js"></script>
<script src="almond.js"></script>
<script src="main-optimized.js"></script>
<script src="yepnope.js"></script>
<script>
    yepnope({
         load: [
             "undersocre+backbone.js",
             "almond.js",
             "main-optimized.js"
         ]
    });
</script>
Questions?
Thank You

Más contenido relacionado

La actualidad más candente

Node.js in a heterogeneous system
Node.js in a heterogeneous systemNode.js in a heterogeneous system
Node.js in a heterogeneous system
GeeksLab Odessa
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
Tom Croucher
 

La actualidad más candente (20)

Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
 
Node.js in a heterogeneous system
Node.js in a heterogeneous systemNode.js in a heterogeneous system
Node.js in a heterogeneous system
 
Node.js in a heterogeneous system
Node.js in a heterogeneous systemNode.js in a heterogeneous system
Node.js in a heterogeneous system
 
Node.js debugging
Node.js debuggingNode.js debugging
Node.js debugging
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
One step in the future: CSS variables
One step in the future: CSS variablesOne step in the future: CSS variables
One step in the future: CSS variables
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to now
 
Node4J: Running Node.js in a JavaWorld
Node4J: Running Node.js in a JavaWorldNode4J: Running Node.js in a JavaWorld
Node4J: Running Node.js in a JavaWorld
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Webdriver.io
Webdriver.io Webdriver.io
Webdriver.io
 
Bundle your modules with Webpack
Bundle your modules with WebpackBundle your modules with Webpack
Bundle your modules with Webpack
 
Webpack: your final module bundler
Webpack: your final module bundlerWebpack: your final module bundler
Webpack: your final module bundler
 
Bower & Grunt - A practical workflow
Bower & Grunt - A practical workflowBower & Grunt - A practical workflow
Bower & Grunt - A practical workflow
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
 
Webpack
Webpack Webpack
Webpack
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!
 

Destacado

Destacado (14)

혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
第4回REST勉強会 RequireJS編
第4回REST勉強会 RequireJS編第4回REST勉強会 RequireJS編
第4回REST勉強会 RequireJS編
 
Becoming Node.js ninja on Cloud Foundry
Becoming Node.js ninja on Cloud FoundryBecoming Node.js ninja on Cloud Foundry
Becoming Node.js ninja on Cloud Foundry
 
Node.js 시작하기
Node.js 시작하기Node.js 시작하기
Node.js 시작하기
 
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
 

Similar a Module, AMD, RequireJS

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
 

Similar a Module, AMD, RequireJS (20)

RequireJS
RequireJSRequireJS
RequireJS
 
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
 
JavaScript Modules in Practice
JavaScript Modules in PracticeJavaScript Modules in Practice
JavaScript Modules in Practice
 
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...
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
Sails js
Sails jsSails js
Sails js
 
Developing Rest services with SailsJs by Andrey Kolodnitskiy
Developing Rest services with SailsJs by Andrey KolodnitskiyDeveloping Rest services with SailsJs by Andrey Kolodnitskiy
Developing Rest services with SailsJs by Andrey Kolodnitskiy
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache Usergrid
 
A nodejs application
A nodejs applicationA nodejs application
A nodejs application
 
Creating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSCreating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJS
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Webpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of usWebpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of us
 
Gradle
GradleGradle
Gradle
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 

Más de 偉格 高 (14)

node ffi
node ffinode ffi
node ffi
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Web Component
Web ComponentWeb Component
Web Component
 
Mobile web application
Mobile web applicationMobile web application
Mobile web application
 
this
thisthis
this
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Vim Plugin Deployment
Vim Plugin DeploymentVim Plugin Deployment
Vim Plugin Deployment
 
WAI-ARIA is More Than Accessibility
WAI-ARIA is More Than AccessibilityWAI-ARIA is More Than Accessibility
WAI-ARIA is More Than Accessibility
 
WAI-ARIA
WAI-ARIAWAI-ARIA
WAI-ARIA
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features
 
Base2
Base2Base2
Base2
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Module, AMD, RequireJS