Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
JavaScript Essential Patterns
Search
othree
April 15, 2012
Technology
12
4.8k
JavaScript Essential Patterns
Talk about the custom event, deferred and pubsub.
othree
April 15, 2012
Tweet
Share
More Decks by othree
See All by othree
How GitHub Supports Vim License Detection, The Five Years Journey
othree
1
1.8k
WAT JavaScript Date
othree
3
1.9k
Modern HTML Email Development
othree
3
2.6k
MRT & GIT
othree
1
2k
YAJS.vim and Vim Syntax Highlight
othree
1
2.6k
Web Trends to 2015
othree
4
310
Transducer
othree
9
2.8k
HITCON 11 Photographer
othree
4
460
fetch is the new XHR
othree
6
3.5k
Other Decks in Technology
See All in Technology
Snowflake女子会#3 Snowpipeの良さを5分で語るよ
lana2548
0
220
フロントエンド設計にモブ設計を導入してみた / 20241212_cloudsign_TechFrontMeetup
bengo4com
0
1.9k
組織に自動テストを書く文化を根付かせる戦略(2024冬版) / Building Automated Test Culture 2024 Winter Edition
twada
PRO
12
3.3k
Wvlet: A New Flow-Style Query Language For Functional Data Modeling and Interactive Data Analysis - Trino Summit 2024
xerial
1
110
マイクロサービスにおける容易なトランザクション管理に向けて
scalar
0
110
サーバレスアプリ開発者向けアップデートをキャッチアップしてきた #AWSreInvent #regrowth_fuk
drumnistnakano
0
190
Oracle Cloud Infrastructure:2024年12月度サービス・アップデート
oracle4engineer
PRO
0
160
Turing × atmaCup #18 - 1st Place Solution
hakubishin3
0
470
生成AIをより賢く エンジニアのための RAG入門 - Oracle AI Jam Session #20
kutsushitaneko
4
210
NW-JAWS #14 re:Invent 2024(予選落ち含)で 発表された推しアップデートについて
nagisa53
0
250
Storage Browser for Amazon S3
miu_crescent
1
130
AI時代のデータセンターネットワーク
lycorptech_jp
PRO
1
280
Featured
See All Featured
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
The Cult of Friendly URLs
andyhume
78
6.1k
Into the Great Unknown - MozCon
thekraken
33
1.5k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
330
21k
No one is an island. Learnings from fostering a developers community.
thoeni
19
3k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
169
50k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
2
160
Bootstrapping a Software Product
garrettdimon
PRO
305
110k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Agile that works and the tools we love
rasmusluckow
328
21k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
247
1.3M
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
28
900
Transcript
JavaScript Essential Patterns othree @ OSDC 2012
Who am I • othree • MozTW member • F2E
at HTC • http://blog.othree.net
Evolution of the Web 1990 1995 2003 2005 WWW Browser
Wars Web Standards Web Applications 2006 Web 2.0 2010 Mobile
Web Applications
Text
None
None
None
None
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 • UI • UI logic
• mutation • ... • BOM Events • load • error • 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
signin signin A Y X Z B
X, Y depends on A
PubSub Subscribe Event Only
PubSub A Y X Z B
PubSub subscribe ‘signin’ subscribe ‘signin’ A Y X Z B
PubSub publish ‘signin’ A Y X Z B
PubSub signin signin A Y X Z B
Publish/Subscribe • Mediator + Observer • Easy to implement
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');
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...
None
None
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