Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Forked from cowboy/HEY-YOU.md
Created October 27, 2011 10:10
Show Gist options
  • Save addyosmani/1319216 to your computer and use it in GitHub Desktop.
Save addyosmani/1319216 to your computer and use it in GitHub Desktop.
jQuery Tiny Pub/Sub: A really, really, REALLY tiny pub/sub implementation for jQuery 1.7
/*!
* jQuery Tiny Pub/Sub - v0.1pre - 11/3/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){
var w = $(window);
$.subscribe = function(){
w.bind.apply( w, arguments );
};
$.publish = function(){
w.trigger.apply( w, arguments );
};
$.unpublish = function(){
w.unbind.apply( w, arguments );
};
})(jQuery);
@addyosmani
Copy link
Author

Note: As jQuery 1.7 pipes all calls to .bind()/.unbind()/.delegate()/.live() etc. through to the rewritten events API (namely .on()/.off()), this is an update to Ben's original solution that directly uses .on() and .off() rather than having an additional layer of abstraction to accessing those methods. That said, the original REALLY tiny pub/sub will still continue to work as the API if of course backwards compatible.

@addyosmani
Copy link
Author

@addyosmani
Copy link
Author

Note 2: This is really just a proof of concept. I would almost always recommend using the original (unless we can show there are significant perf benefits to using .on/.off directly over the (now) abstracted .bind()/.unbind() versions etc).

@elijahmanor
Copy link

@addy: My guess is that the on/off implementation above should be faster when compared to the previous implementation (bind/unbind) using 1.7. It should only be slightly faster because bind/unbind are just one line wrappers around the on/off methods http://o61.go.ly

With that in mind the on/off methods in 1.7 could very well be slower than the bind/unbind methods in 1.6.4. That would be an interesting comparison. I hope the answer is better performance in 1.7 & not worse ;)

@albanx
Copy link

albanx commented Mar 15, 2014

Hi Andy
Excellent pattern. BUt I am having some problems on the context of the callback function. Example:
$.subscribe("dashboard.updateData", this.updateData ); //this--> currenct object

then :
updateData: function(){
this--> here is the event object, but here I will need the original object
}

Is there a way to make callbacks fire in scope of originating object instead ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment