SlideShare a Scribd company logo
JavaScript Essential Patterns
        othree @ OSDC 2012
Who am I

• othree
• MozTW member
• F2E at HTC
• http://blog.othree.net
Evolution of the Web
WWW
   Browser Wars
         Web Standards
                Web Applications
                          Web 2.0
                                    Mobile

1990   1995   2003   2005   2006    2010
Web Applications
Text
Problem to F2E


• Large scale application never seen on Web
But


• The problem F2Es face today already exists
What is Pattern


• A general reusable solution to a commonly
  occurring problem within a given context in
  software design.




                     http://en.wikipedia.org/wiki/Software_design_pattern
GOF Book, 1994
Browser Environment
• Async
 • Event Driven
• Async
 • Source Code from Internet
• Async
 • Business Logic on Server
Patterns to Talk Today

• Custom Event
• Deferred
• PubSub
Custom Event



     http://www.flickr.com/photos/swehrmann/6009646752
Event


• Something happens to an element, to the
  main document, or to the browser window
  and that event triggers a reaction.




                     http://www.yuiblog.com/blog/2007/01/17/event-plan/
Native Events

•   DOM Events       •   BOM Events

    •   UI               •   load

    •   UI logic         •   error

    •   mutation         •   history

    •   ...              •   ...
Problem of IE

• Didn’t follow the W3C DOM standard
• Memory leaks
• Not support bubbling/capturing
• ‘this’ is window, not element
• ‘event’ is different
         http://www.quirksmode.org/blog/archives/2005/08/addevent_consid.html
Dean Edward’s Add Event


• Manage callback functions
• Fallback to elem.onevent = function () { ... }
• Only one function for each event

                      http://dean.edwards.name/weblog/2005/10/add-event2/
jQuery’s Event


• Normalize event object
• ‘trigger’ method to fire specific event
‘trigger’ Method


• Can fire any event as you wish
• Even none native event name works
Custom Event


• An event name is defined by you, triggered
  by you
When to Trigger


• State/Value change
Observer

• Define a one-to-many dependency between
  objects so that when one object changes
  state, all its dependents are notified and
  updated automatically.




                                              GoF Book
Example: Backbone

• A driver model
• A car model
• Driver’s tension will get higher when shift
  gear
Driver
var Driver = Backbone.Model.extend(
    defaults: {
        tension: 0
    },
    tensionUp: function () {
        this.set({
            tension: this.get('tension') + 1
        });
    }
);
Car
var Car = Backbone.Model.extend(
    defaults: {
        gear: 'P'
    }
);
Observer
var driver = new Driver(),
    car = new Car();

car.on('change:gear', function () {
    driver.tensionUp();
});

//GO
car.set({
     gear: 1
});
Advantages


• Loose coupling
• Prevent nested codes
Deferred



   http://www.flickr.com/photos/gozalewis/3256814461/
History

• a.k.a Promise
• Idea since 1976 (Call by future)
• Dojo 0.9 (2007), 1.5 (2010)
• jQuery 1.5 (2011)
• CommonJS Promises/A
What is Deferred

• In computer science, future, promise, and
  delay refer to constructs used for
  synchronization in some concurrent
  programming languages.




                       http://en.wikipedia.org/wiki/Futures_and_promises
Example: Image Loader
function imgLoader(src) {
    var _img = new Image(),
        _def = $.Deferred();

     _img.onload = _def.resolve; //success
     _img.onerror = _def.reject; //fail

     _img.src = src

     return _def;
}
Use Image Loader
imgLoader('/images/logo.png').done(function () {

      $('#logo').fadeIn();

}).fail(function () {

      document.location = '/404.html';

});
jQuery Deferred

• Multiple callback functions
• Add callbacks at any time
• jQuery.when

                         http://api.jquery.com/category/deferred-object/
Image Loader with Cache
function imgLoader(src) {
    if (imgLoader[src]) {
        return imgLoader[src];
    }

    var _img = new Image(),
        _def = $.Deferred();

    imgLoader[src] = _def;

    _img.onload = _def.resolve; //success
    _img.onerror = _def.reject; //fail

    _img.src = src
    return _def;
}
Use Image Loader
imgLoader('/images/logo.png').done(function () {
    $('#logo').fadeIn();
}).fail(function () {
    document.location = '/404.html';
});

imgLoader('/images/logo.png').done(function () {
    App.init();
});

imgLoader('/images/logo.png').fail(function () {
    App.destroy();
});
jQuery.when
$.when(

      $.getJSON('/api/jedis'),
      $.getJSON('/api/siths'),
      $.getJSON('/api/terminators')

).done(function (jedis, siths, terminators) {

      // do something....

});
Advantages

• Manage callbacks
• Cache results
• $.when
PubSub



   http://www.flickr.com/photos/birdfarm/519230710/
Case

• A module know when user signin
• X,Y modules need to know when user
  signin
• A should not fail when X or Y fails
Without PubSub
X
    signin

    signin
A            Y




B            Z
X,Y depends on A
PubSub
Subscribe Event Only
X


    PubSub

A            Y




B            Z
subscribe
              ‘signin’
                           X


    PubSub
               subscribe
A               ‘signin’   Y




B                          Z
X


               PubSub
    publish
A   ‘signin’            Y




B                       Z
signin     X


    PubSub
               signin
A                       Y




B                       Z
Publish/Subscribe


• Mediator + Observer
• Easy to implement
$(document).trigger('eventName');               // Using .on()/.off() from jQuery 1.7.1
//equivalent to $.publish('eventName')          (function($) {
$(document).on('eventName',...);                  var o = $({});
//equivalent to $.subscribe('eventName',...)      $.subscribe = function() {
                                                     o.on.apply(o, arguments);
                                                  };
                                                  $.unsubscribe = function() {
                                                     o.off.apply(o, arguments);
                                                  };
                                                  $.publish = function() {
                                                     o.trigger.apply(o, arguments);
                                                  };
                                                }(jQuery));




// Multi-purpose callbacks list object          //Using Underscore and Backbone
// Pub/Sub implementation:
                                                var myObject = {};
var topics = {};
                                                _.extend( myObject, Backbone.Events );
jQuery.Topic = function( id ) {
   var callbacks,
        topic = id && topics[ id ];             //Example
   if ( !topic ) {
     callbacks = jQuery.Callbacks();            myObject.on('eventName', function( msg ) {
     topic = {                                      console.log( 'triggered:' + msg );
        publish: callbacks.fire,                });
        subscribe: callbacks.add,
        unsubscribe: callbacks.remove           myObject.trigger('eventName', 'some event');
     };
     if ( id ) {
        topics[ id ] = topic;
     }
   }
   return topic;
};
                                               http://addyosmani.com/blog/jqcon-largescalejs-2012/
When to Use


• Module and module have dependency but
  not really depend on it.
Example: Error Handler

• An module to control the behavior when
  error occurs
• All other module should call it when
  something went wrong
• No module should fail because error
  handler fails
Error Handler Code
//Error Handler
$.subscribe('AJAXfail', function () {
    alert('Something wrong!!');
});



//Code
$.get('/api/siths').fail(function () {
    $.publish('AJAXfail');
});
Advantages


• Loose coupling
• Scalability
Summary

• Control async process using deferred
• Modulize your application
• Decouple using custom event
• Decouple more using pubsub
Further Reading...
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
http://shichuan.github.com/javascript-patterns/
http://leanpub.com/asyncjs
May the Patterns be with You
Questions?
Photos License

• CC License
 •   http://www.flickr.com/photos/sbisson/298160250/

 •   http://www.flickr.com/photos/gozalewis/3256814461/

 •   http://www.flickr.com/photos/birdfarm/519230710/


• Licensed by Author
 •   http://www.flickr.com/photos/swehrmann/6009646752

More Related Content

What's hot

The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
Derek Lee Boire
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
Konstantin Kudryashov
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
Dmitry Baranovskiy
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
Rebecca Murphey
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
Diego Fleury
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
Brian Lonsdorf
 
Lenses
LensesLenses

What's hot (20)

The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Lenses
LensesLenses
Lenses
 

Similar to Javascript essential-pattern

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinar
Yonni Mendes
 
YUI 3
YUI 3YUI 3
YUI 3
Dav Glass
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Frédéric Harper
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
Steve McMahon
 
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
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
Doris Chen
 
YUI (Advanced)
YUI (Advanced)YUI (Advanced)
YUI (Advanced)
Jai Santhosh
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
Keith Bloomfield
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
Ross Bruniges
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
Doris Chen
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 

Similar to Javascript essential-pattern (20)

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinar
 
YUI 3
YUI 3YUI 3
YUI 3
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
 
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...
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
JS Essence
JS EssenceJS Essence
JS Essence
 
YUI (Advanced)
YUI (Advanced)YUI (Advanced)
YUI (Advanced)
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 

More from 偉格 高

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偉格 高
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013偉格 高
 
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
偉格 高
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單
偉格 高
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features偉格 高
 
Base2
Base2Base2
Base2
偉格 高
 

More from 偉格 高 (11)

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
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013
 
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
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

Javascript essential-pattern

  • 1. JavaScript Essential Patterns othree @ OSDC 2012
  • 2. Who am I • othree • MozTW member • F2E at HTC • http://blog.othree.net
  • 3. Evolution of the Web WWW Browser Wars Web Standards Web Applications Web 2.0 Mobile 1990 1995 2003 2005 2006 2010
  • 6.
  • 7.
  • 8.
  • 9.
  • 10. Problem to F2E • Large scale application never seen on Web
  • 11. But • The problem F2Es face today already exists
  • 12. What is Pattern • A general reusable solution to a commonly occurring problem within a given context in software design. http://en.wikipedia.org/wiki/Software_design_pattern
  • 14. Browser Environment • Async • Event Driven • Async • Source Code from Internet • Async • Business Logic on Server
  • 15. Patterns to Talk Today • Custom Event • Deferred • PubSub
  • 16. Custom Event http://www.flickr.com/photos/swehrmann/6009646752
  • 17. Event • Something happens to an element, to the main document, or to the browser window and that event triggers a reaction. http://www.yuiblog.com/blog/2007/01/17/event-plan/
  • 18. Native Events • DOM Events • BOM Events • UI • load • UI logic • error • mutation • history • ... • ...
  • 19. Problem of IE • Didn’t follow the W3C DOM standard • Memory leaks • Not support bubbling/capturing • ‘this’ is window, not element • ‘event’ is different http://www.quirksmode.org/blog/archives/2005/08/addevent_consid.html
  • 20. Dean Edward’s Add Event • Manage callback functions • Fallback to elem.onevent = function () { ... } • Only one function for each event http://dean.edwards.name/weblog/2005/10/add-event2/
  • 21. jQuery’s Event • Normalize event object • ‘trigger’ method to fire specific event
  • 22. ‘trigger’ Method • Can fire any event as you wish • Even none native event name works
  • 23. Custom Event • An event name is defined by you, triggered by you
  • 24. When to Trigger • State/Value change
  • 25. Observer • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. GoF Book
  • 26. Example: Backbone • A driver model • A car model • Driver’s tension will get higher when shift gear
  • 27. Driver var Driver = Backbone.Model.extend( defaults: { tension: 0 }, tensionUp: function () { this.set({ tension: this.get('tension') + 1 }); } );
  • 28. Car var Car = Backbone.Model.extend( defaults: { gear: 'P' } );
  • 29. Observer var driver = new Driver(), car = new Car(); car.on('change:gear', function () { driver.tensionUp(); }); //GO car.set({ gear: 1 });
  • 30. Advantages • Loose coupling • Prevent nested codes
  • 31. Deferred http://www.flickr.com/photos/gozalewis/3256814461/
  • 32. History • a.k.a Promise • Idea since 1976 (Call by future) • Dojo 0.9 (2007), 1.5 (2010) • jQuery 1.5 (2011) • CommonJS Promises/A
  • 33. What is Deferred • In computer science, future, promise, and delay refer to constructs used for synchronization in some concurrent programming languages. http://en.wikipedia.org/wiki/Futures_and_promises
  • 34. Example: Image Loader function imgLoader(src) { var _img = new Image(), _def = $.Deferred(); _img.onload = _def.resolve; //success _img.onerror = _def.reject; //fail _img.src = src return _def; }
  • 35. Use Image Loader imgLoader('/images/logo.png').done(function () { $('#logo').fadeIn(); }).fail(function () { document.location = '/404.html'; });
  • 36. jQuery Deferred • Multiple callback functions • Add callbacks at any time • jQuery.when http://api.jquery.com/category/deferred-object/
  • 37. Image Loader with Cache function imgLoader(src) { if (imgLoader[src]) { return imgLoader[src]; } var _img = new Image(), _def = $.Deferred(); imgLoader[src] = _def; _img.onload = _def.resolve; //success _img.onerror = _def.reject; //fail _img.src = src return _def; }
  • 38. Use Image Loader imgLoader('/images/logo.png').done(function () { $('#logo').fadeIn(); }).fail(function () { document.location = '/404.html'; }); imgLoader('/images/logo.png').done(function () { App.init(); }); imgLoader('/images/logo.png').fail(function () { App.destroy(); });
  • 39. jQuery.when $.when( $.getJSON('/api/jedis'), $.getJSON('/api/siths'), $.getJSON('/api/terminators') ).done(function (jedis, siths, terminators) { // do something.... });
  • 40. Advantages • Manage callbacks • Cache results • $.when
  • 41. PubSub http://www.flickr.com/photos/birdfarm/519230710/
  • 42. Case • A module know when user signin • X,Y modules need to know when user signin • A should not fail when X or Y fails
  • 44. X signin signin A Y B Z
  • 47. X PubSub A Y B Z
  • 48. subscribe ‘signin’ X PubSub subscribe A ‘signin’ Y B Z
  • 49. X PubSub publish A ‘signin’ Y B Z
  • 50. signin X PubSub signin A Y B Z
  • 51. Publish/Subscribe • Mediator + Observer • Easy to implement
  • 52. $(document).trigger('eventName'); // Using .on()/.off() from jQuery 1.7.1 //equivalent to $.publish('eventName') (function($) { $(document).on('eventName',...); var o = $({}); //equivalent to $.subscribe('eventName',...) $.subscribe = function() { o.on.apply(o, arguments); }; $.unsubscribe = function() { o.off.apply(o, arguments); }; $.publish = function() { o.trigger.apply(o, arguments); }; }(jQuery)); // Multi-purpose callbacks list object //Using Underscore and Backbone // Pub/Sub implementation: var myObject = {}; var topics = {}; _.extend( myObject, Backbone.Events ); jQuery.Topic = function( id ) { var callbacks, topic = id && topics[ id ]; //Example if ( !topic ) { callbacks = jQuery.Callbacks(); myObject.on('eventName', function( msg ) { topic = { console.log( 'triggered:' + msg ); publish: callbacks.fire, }); subscribe: callbacks.add, unsubscribe: callbacks.remove myObject.trigger('eventName', 'some event'); }; if ( id ) { topics[ id ] = topic; } } return topic; }; http://addyosmani.com/blog/jqcon-largescalejs-2012/
  • 53. When to Use • Module and module have dependency but not really depend on it.
  • 54. Example: Error Handler • An module to control the behavior when error occurs • All other module should call it when something went wrong • No module should fail because error handler fails
  • 55. Error Handler Code //Error Handler $.subscribe('AJAXfail', function () { alert('Something wrong!!'); }); //Code $.get('/api/siths').fail(function () { $.publish('AJAXfail'); });
  • 57. Summary • Control async process using deferred • Modulize your application • Decouple using custom event • Decouple more using pubsub
  • 59.
  • 60.
  • 64. May the Patterns be with You
  • 66. Photos License • CC License • http://www.flickr.com/photos/sbisson/298160250/ • http://www.flickr.com/photos/gozalewis/3256814461/ • http://www.flickr.com/photos/birdfarm/519230710/ • Licensed by Author • http://www.flickr.com/photos/swehrmann/6009646752