-
-
Save addyosmani/1319216 to your computer and use it in GitHub Desktop.
| /*! | |
| * 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); |
And demo: http://jsfiddle.net/58RnW/
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).
@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 ;)
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 ?
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.