SlideShare une entreprise Scribd logo
1  sur  66
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in SwiftDerek Lee Boire
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan 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 mockingKonstantin Kudryashov
 
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 DevsRebecca 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
 
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 DICKonstantin Kudryashov
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace PatternDiego Fleury
 

Tendances (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
 

Similaire à Javascript essential-pattern

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
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 & AngularErik 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 webinarYonni Mendes
 
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-28Frédéric Harper
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MySteve 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
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia 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
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
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 suckRoss 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 #d8rulesSrijan Technologies
 

Similaire à 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
 

Plus de 偉格 高

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偉格 高
 

Plus de 偉格 高 (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
 

Dernier

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 AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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 textsMaria Levchenko
 
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.pdfsudhanshuwaghmare1
 
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 MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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 Servicegiselly40
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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