Slide 1

Slide 1 text

JavaScript Essential Patterns othree @ OSDC 2012

Slide 2

Slide 2 text

Who am I • othree • MozTW member • F2E at HTC • http://blog.othree.net

Slide 3

Slide 3 text

Evolution of the Web 1990 1995 2003 2005 WWW Browser Wars Web Standards Web Applications 2006 Web 2.0 2010 Mobile

Slide 4

Slide 4 text

Web Applications

Slide 5

Slide 5 text

Text

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

Problem to F2E • Large scale application never seen on Web

Slide 11

Slide 11 text

But • The problem F2Es face today already exists

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

GOF Book, 1994

Slide 14

Slide 14 text

Browser Environment • Async • Event Driven • Async • Source Code from Internet • Async • Business Logic on Server

Slide 15

Slide 15 text

Patterns to Talk Today • Custom Event • Deferred • PubSub

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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/

Slide 18

Slide 18 text

Native Events • DOM Events • UI • UI logic • mutation • ... • BOM Events • load • error • history • ...

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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/

Slide 21

Slide 21 text

jQuery’s Event • Normalize event object • ‘trigger’ method to fire specific event

Slide 22

Slide 22 text

‘trigger’ Method • Can fire any event as you wish • Even none native event name works

Slide 23

Slide 23 text

Custom Event • An event name is defined by you, triggered by you

Slide 24

Slide 24 text

When to Trigger • State/Value change

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

Example: Backbone • A driver model • A car model • Driver’s tension will get higher when shift gear

Slide 27

Slide 27 text

Driver var Driver = Backbone.Model.extend( defaults: { tension: 0 }, tensionUp: function () { this.set({ tension: this.get('tension') + 1 }); } );

Slide 28

Slide 28 text

Car var Car = Backbone.Model.extend( defaults: { gear: 'P' } );

Slide 29

Slide 29 text

Observer var driver = new Driver(), car = new Car(); car.on('change:gear', function () { driver.tensionUp(); }); //GO car.set({ gear: 1 });

Slide 30

Slide 30 text

Advantages • Loose coupling • Prevent nested codes

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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; }

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

jQuery Deferred • Multiple callback functions • Add callbacks at any time • jQuery.when http://api.jquery.com/category/deferred-object/

Slide 37

Slide 37 text

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; }

Slide 38

Slide 38 text

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(); });

Slide 39

Slide 39 text

jQuery.when $.when( $.getJSON('/api/jedis'), $.getJSON('/api/siths'), $.getJSON('/api/terminators') ).done(function (jedis, siths, terminators) { // do something.... });

Slide 40

Slide 40 text

Advantages • Manage callbacks • Cache results • $.when

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

Without PubSub

Slide 44

Slide 44 text

signin signin A Y X Z B

Slide 45

Slide 45 text

X, Y depends on A

Slide 46

Slide 46 text

PubSub Subscribe Event Only

Slide 47

Slide 47 text

PubSub A Y X Z B

Slide 48

Slide 48 text

PubSub subscribe ‘signin’ subscribe ‘signin’ A Y X Z B

Slide 49

Slide 49 text

PubSub publish ‘signin’ A Y X Z B

Slide 50

Slide 50 text

PubSub signin signin A Y X Z B

Slide 51

Slide 51 text

Publish/Subscribe • Mediator + Observer • Easy to implement

Slide 52

Slide 52 text

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');

Slide 53

Slide 53 text

When to Use • Module and module have dependency but not really depend on it.

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

Error Handler Code //Error Handler $.subscribe('AJAXfail', function () { alert('Something wrong!!'); }); //Code $.get('/api/siths').fail(function () { $.publish('AJAXfail'); });

Slide 56

Slide 56 text

Advantages • Loose coupling • Scalability

Slide 57

Slide 57 text

Summary • Control async process using deferred • Modulize your application • Decouple using custom event • Decouple more using pubsub

Slide 58

Slide 58 text

Further Reading...

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Slide 62

Slide 62 text

http://shichuan.github.com/javascript-patterns/

Slide 63

Slide 63 text

http://leanpub.com/asyncjs

Slide 64

Slide 64 text

May the Patterns be with You

Slide 65

Slide 65 text

Questions?

Slide 66

Slide 66 text

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