javascript essential-pattern
DESCRIPTION
Talk about the custom event, deferred and pubsub.TRANSCRIPT
![Page 1: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/1.jpg)
JavaScript Essential Patternsothree @ OSDC 2012
![Page 2: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/2.jpg)
Who am I
• othree
• MozTW member
• F2E at HTC
• http://blog.othree.net
![Page 3: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/3.jpg)
Evolution of the Web
1990 1995 2003 2005
WWWBrowser Wars
Web StandardsWeb Applications
2006
Web 2.0
2010
Mobile
![Page 4: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/4.jpg)
Web Applications
![Page 5: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/5.jpg)
Text
![Page 6: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/6.jpg)
![Page 7: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/7.jpg)
![Page 8: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/8.jpg)
![Page 9: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/9.jpg)
![Page 10: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/10.jpg)
Problem to F2E
• Large scale application never seen on Web
![Page 11: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/11.jpg)
But
• The problem F2Es face today already exists
![Page 12: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/12.jpg)
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
![Page 13: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/13.jpg)
GOF Book, 1994
![Page 14: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/14.jpg)
Browser Environment
• Async
• Event Driven
• Async
• Source Code from Internet
• Async
• Business Logic on Server
![Page 15: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/15.jpg)
Patterns to Talk Today
• Custom Event
• Deferred
• PubSub
![Page 16: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/16.jpg)
Custom Event
http://www.flickr.com/photos/swehrmann/6009646752
![Page 17: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/17.jpg)
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/
![Page 18: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/18.jpg)
Native Events
• DOM Events
• UI
• UI logic
• mutation
• ...
• BOM Events
• load
• error
• history
• ...
![Page 19: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/19.jpg)
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
![Page 20: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/20.jpg)
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/
![Page 21: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/21.jpg)
jQuery’s Event
• Normalize event object
• ‘trigger’ method to fire specific event
![Page 22: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/22.jpg)
‘trigger’ Method
• Can fire any event as you wish
• Even none native event name works
![Page 23: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/23.jpg)
Custom Event
• An event name is defined by you, triggered by you
![Page 24: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/24.jpg)
When to Trigger
• State/Value change
![Page 25: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/25.jpg)
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
![Page 26: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/26.jpg)
Example: Backbone
• A driver model
• A car model
• Driver’s tension will get higher when shift gear
![Page 27: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/27.jpg)
Drivervar Driver = Backbone.Model.extend( defaults: { tension: 0 }, tensionUp: function () { this.set({ tension: this.get('tension') + 1 }); });
![Page 28: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/28.jpg)
Carvar Car = Backbone.Model.extend( defaults: { gear: 'P' });
![Page 29: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/29.jpg)
Observervar driver = new Driver(), car = new Car();
car.on('change:gear', function () { driver.tensionUp();});
//GOcar.set({ gear: 1});
![Page 30: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/30.jpg)
Advantages
• Loose coupling
• Prevent nested codes
![Page 31: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/31.jpg)
Deferred
http://www.flickr.com/photos/gozalewis/3256814461/
![Page 32: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/32.jpg)
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
![Page 33: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/33.jpg)
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
![Page 34: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/34.jpg)
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;}
![Page 35: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/35.jpg)
Use Image LoaderimgLoader('/images/logo.png').done(function () {
$('#logo').fadeIn();
}).fail(function () {
document.location = '/404.html';
});
![Page 36: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/36.jpg)
jQuery Deferred
• Multiple callback functions
• Add callbacks at any time
• jQuery.when
http://api.jquery.com/category/deferred-object/
![Page 37: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/37.jpg)
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;}
![Page 38: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/38.jpg)
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();});
![Page 39: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/39.jpg)
jQuery.when$.when(
$.getJSON('/api/jedis'), $.getJSON('/api/siths'), $.getJSON('/api/terminators')
).done(function (jedis, siths, terminators) {
// do something....
});
![Page 40: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/40.jpg)
Advantages
• Manage callbacks
• Cache results
• $.when
![Page 41: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/41.jpg)
PubSub
http://www.flickr.com/photos/birdfarm/519230710/
![Page 42: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/42.jpg)
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
![Page 43: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/43.jpg)
Without PubSub
![Page 44: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/44.jpg)
signin
signin
A Y
X
ZB
![Page 45: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/45.jpg)
X, Y depends on A
![Page 46: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/46.jpg)
PubSubSubscribe Event Only
![Page 47: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/47.jpg)
PubSub
A Y
X
ZB
![Page 48: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/48.jpg)
PubSubsubscribe
‘signin’
subscribe‘signin’
A Y
X
ZB
![Page 49: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/49.jpg)
PubSubpublish‘signin’A Y
X
ZB
![Page 50: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/50.jpg)
PubSubsignin
signin
A Y
X
ZB
![Page 51: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/51.jpg)
Publish/Subscribe
• Mediator + Observer
• Easy to implement
![Page 52: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/52.jpg)
http://addyosmani.com/blog/jqcon-largescalejs-2012/
$(document).trigger('eventName');//equivalent to $.publish('eventName')$(document).on('eventName',...);//equivalent to $.subscribe('eventName',...)
// Using .on()/.off() from jQuery 1.7.1(function($) { var o = $({}); $.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// Pub/Sub implementation:
var topics = {};
jQuery.Topic = function( id ) { var callbacks, topic = id && topics[ id ]; if ( !topic ) { callbacks = jQuery.Callbacks(); topic = { publish: callbacks.fire, subscribe: callbacks.add, unsubscribe: callbacks.remove }; if ( id ) { topics[ id ] = topic; } } return topic;};
//Using Underscore and Backbone
var myObject = {};
_.extend( myObject, Backbone.Events );
//Example
myObject.on('eventName', function( msg ) { console.log( 'triggered:' + msg );});
myObject.trigger('eventName', 'some event');
![Page 53: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/53.jpg)
When to Use
• Module and module have dependency but not really depend on it.
![Page 54: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/54.jpg)
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
![Page 55: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/55.jpg)
Error Handler Code//Error Handler$.subscribe('AJAXfail', function () { alert('Something wrong!!');});
//Code$.get('/api/siths').fail(function () { $.publish('AJAXfail');});
![Page 56: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/56.jpg)
Advantages
• Loose coupling
• Scalability
![Page 57: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/57.jpg)
Summary
• Control async process using deferred
• Modulize your application
• Decouple using custom event
• Decouple more using pubsub
![Page 58: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/58.jpg)
Further Reading...
![Page 59: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/59.jpg)
![Page 60: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/60.jpg)
![Page 61: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/61.jpg)
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
![Page 62: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/62.jpg)
http://shichuan.github.com/javascript-patterns/
![Page 64: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/64.jpg)
May the Patterns be with You
![Page 65: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/65.jpg)
Questions?
![Page 66: Javascript essential-pattern](https://reader033.vdocuments.net/reader033/viewer/2022051514/54b7a5024a795993718b47f9/html5/thumbnails/66.jpg)
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