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