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