JavaScript Essential Patterns        othree @ OSDC 2012
Who am I• othree• MozTW member• F2E at HTC• http://blog.othree.net
Evolution of the WebWWW   Browser Wars         Web Standards                Web Applications                          Web ...
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. ...
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 reactio...
Native Events•   DOM Events       •   BOM Events    •   UI               •   load    •   UI logic         •   error    •  ...
Problem of IE• Didn’t follow the W3C DOM standard• Memory leaks• Not support bubbling/capturing• ‘this’ is window, not ele...
Dean Edward’s Add Event• Manage callback functions• Fallback to elem.onevent = function () { ... }• Only one function for ...
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 n...
Example: Backbone• A driver model• A car model• Driver’s tension will get higher when shift  gear
Drivervar Driver = Backbone.Model.extend(    defaults: {        tension: 0    },    tensionUp: function () {        this.s...
Carvar Car = Backbone.Model.extend(    defaults: {        gear: P    });
Observervar driver = new Driver(),    car = new Car();car.on(change:gear, function () {    driver.tensionUp();});//GOcar.s...
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 Promise...
What is Deferred• In computer science, future, promise, and  delay refer to constructs used for  synchronization in some c...
Example: Image Loaderfunction imgLoader(src) {    var _img = new Image(),        _def = $.Deferred();     _img.onload = _d...
Use Image LoaderimgLoader(/images/logo.png).done(function () {      $(#logo).fadeIn();}).fail(function () {      document....
jQuery Deferred• Multiple callback functions• Add callbacks at any time• jQuery.when                         http://api.jq...
Image Loader with Cachefunction imgLoader(src) {    if (imgLoader[src]) {        return imgLoader[src];    }    var _img =...
Use Image LoaderimgLoader(/images/logo.png).done(function () {    $(#logo).fadeIn();}).fail(function () {    document.loca...
jQuery.when$.when(      $.getJSON(/api/jedis),      $.getJSON(/api/siths),      $.getJSON(/api/terminators)).done(function...
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    signinA            YB            Z
X,Y depends on A
PubSubSubscribe Event Only
X    PubSubA            YB            Z
subscribe              ‘signin’                           X    PubSub               subscribeA               ‘signin’   YB...
X               PubSub    publishA   ‘signin’            YB                       Z
signin     X    PubSub               signinA                       YB                       Z
Publish/Subscribe• Mediator + Observer• Easy to implement
$(document).trigger(eventName);               // Using .on()/.off() from jQuery 1.7.1//equivalent to $.publish(eventName) ...
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  someth...
Error Handler Code//Error Handler$.subscribe(AJAXfail, function () {    alert(Something wrong!!);});//Code$.get(/api/siths...
Advantages• Loose coupling• Scalability
Summary• Control async process using deferred• Modulize your application• Decouple using custom event• Decouple more using...
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/32...
Javascript essential-pattern
Javascript essential-pattern
Javascript essential-pattern
Javascript essential-pattern
Javascript essential-pattern
Javascript essential-pattern
Upcoming SlideShare
Loading in …5
×

Javascript essential-pattern

2,927 views

Published on

Talk about the custom event, deferred and pubsub.

Published in: Technology
0 Comments
13 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,927
On SlideShare
0
From Embeds
0
Number of Embeds
41
Actions
Shares
0
Downloads
60
Comments
0
Likes
13
Embeds 0
No embeds

No notes for slide

Javascript essential-pattern

  1. 1. JavaScript Essential Patterns othree @ OSDC 2012
  2. 2. Who am I• othree• MozTW member• F2E at HTC• http://blog.othree.net
  3. 3. Evolution of the WebWWW Browser Wars Web Standards Web Applications Web 2.0 Mobile1990 1995 2003 2005 2006 2010
  4. 4. Web Applications
  5. 5. Text
  6. 6. Problem to F2E• Large scale application never seen on Web
  7. 7. But• The problem F2Es face today already exists
  8. 8. 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
  9. 9. GOF Book, 1994
  10. 10. Browser Environment• Async • Event Driven• Async • Source Code from Internet• Async • Business Logic on Server
  11. 11. Patterns to Talk Today• Custom Event• Deferred• PubSub
  12. 12. Custom Event http://www.flickr.com/photos/swehrmann/6009646752
  13. 13. 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/
  14. 14. Native Events• DOM Events • BOM Events • UI • load • UI logic • error • mutation • history • ... • ...
  15. 15. 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
  16. 16. 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/
  17. 17. jQuery’s Event• Normalize event object• ‘trigger’ method to fire specific event
  18. 18. ‘trigger’ Method• Can fire any event as you wish• Even none native event name works
  19. 19. Custom Event• An event name is defined by you, triggered by you
  20. 20. When to Trigger• State/Value change
  21. 21. 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
  22. 22. Example: Backbone• A driver model• A car model• Driver’s tension will get higher when shift gear
  23. 23. Drivervar Driver = Backbone.Model.extend( defaults: { tension: 0 }, tensionUp: function () { this.set({ tension: this.get(tension) + 1 }); });
  24. 24. Carvar Car = Backbone.Model.extend( defaults: { gear: P });
  25. 25. Observervar driver = new Driver(), car = new Car();car.on(change:gear, function () { driver.tensionUp();});//GOcar.set({ gear: 1});
  26. 26. Advantages• Loose coupling• Prevent nested codes
  27. 27. Deferred http://www.flickr.com/photos/gozalewis/3256814461/
  28. 28. 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
  29. 29. 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
  30. 30. Example: Image Loaderfunction imgLoader(src) { var _img = new Image(), _def = $.Deferred(); _img.onload = _def.resolve; //success _img.onerror = _def.reject; //fail _img.src = src return _def;}
  31. 31. Use Image LoaderimgLoader(/images/logo.png).done(function () { $(#logo).fadeIn();}).fail(function () { document.location = /404.html;});
  32. 32. jQuery Deferred• Multiple callback functions• Add callbacks at any time• jQuery.when http://api.jquery.com/category/deferred-object/
  33. 33. Image Loader with Cachefunction 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;}
  34. 34. Use Image LoaderimgLoader(/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();});
  35. 35. jQuery.when$.when( $.getJSON(/api/jedis), $.getJSON(/api/siths), $.getJSON(/api/terminators)).done(function (jedis, siths, terminators) { // do something....});
  36. 36. Advantages• Manage callbacks• Cache results• $.when
  37. 37. PubSub http://www.flickr.com/photos/birdfarm/519230710/
  38. 38. 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
  39. 39. Without PubSub
  40. 40. X signin signinA YB Z
  41. 41. X,Y depends on A
  42. 42. PubSubSubscribe Event Only
  43. 43. X PubSubA YB Z
  44. 44. subscribe ‘signin’ X PubSub subscribeA ‘signin’ YB Z
  45. 45. X PubSub publishA ‘signin’ YB Z
  46. 46. signin X PubSub signinA YB Z
  47. 47. Publish/Subscribe• Mediator + Observer• Easy to implement
  48. 48. $(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/
  49. 49. When to Use• Module and module have dependency but not really depend on it.
  50. 50. 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
  51. 51. Error Handler Code//Error Handler$.subscribe(AJAXfail, function () { alert(Something wrong!!);});//Code$.get(/api/siths).fail(function () { $.publish(AJAXfail);});
  52. 52. Advantages• Loose coupling• Scalability
  53. 53. Summary• Control async process using deferred• Modulize your application• Decouple using custom event• Decouple more using pubsub
  54. 54. Further Reading...
  55. 55. http://addyosmani.com/resources/essentialjsdesignpatterns/book/
  56. 56. http://shichuan.github.com/javascript-patterns/
  57. 57. http://leanpub.com/asyncjs
  58. 58. May the Patterns be with You
  59. 59. Questions?
  60. 60. 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

×