SlideShare ist ein Scribd-Unternehmen logo
1 von 65
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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!
 

Andere mochten auch

Andere mochten auch (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의 장단점과 대안
 

Ähnlich wie 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
 

Ähnlich wie 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
 
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
 
Sails js
Sails jsSails js
Sails js
 
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
 

Mehr von 偉格 高 (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
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Module, AMD, RequireJS