-
-
Save albanx/9563956 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* jQuery Tiny Pub/Sub for jQuery 1.7 - v0.1 - 27/10/2011 | |
* Based on @cowboy Ben Alman's REALLY tiny pub/sub. | |
* 1.7 specific updates by @addyosmani. | |
* Copyright maintained by @cowboy. | |
* Dual licensed under the MIT and GPL licenses. | |
* Edit By Alban to allow object context and return | |
*/ | |
(function($) | |
{ | |
// Create a "dummy" jQuery object on which to call on, off and trigger event | |
// handlers. Although using {} throws errors here in older versions of | |
// jQuery | |
// if you are using 1.7, you won't have this issue. | |
var o = $({}); | |
// Subscribe to a topic. Works just like on, except the passed handler | |
// is wrapped in a function so that the event object can be stripped out. | |
// Even though the event object might be useful, it is unnecessary and | |
// will only complicate things in the future should the user decide to move | |
// to a non-$.event-based pub/sub implementation. | |
$.subscribe = function(topic, context, fn) | |
{ | |
// Call fn, stripping out the 1st argument (the event object). | |
function wrapper() | |
{ | |
if(typeof fn == 'undefined') | |
{ | |
return context.apply(this, Array.prototype.slice.call(arguments, 1)); | |
} | |
else | |
{ | |
if(typeof fn == 'function'){ | |
return fn.apply(context, Array.prototype.slice.call(arguments, 1)); | |
} | |
return context[fn].apply(context, Array.prototype.slice.call(arguments, 1)); | |
} | |
} | |
// Bind the handler. | |
o.on(topic, wrapper); | |
}; | |
// Unsubscribe from a topic. | |
$.unsubscribe = function() | |
{ | |
o.off.apply(o, arguments); | |
}; | |
// Publish a topic | |
$.publish = function() | |
{ | |
return o.triggerHandler.apply(o, arguments); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add context for objects