When reading Pub/Sub library by Ben Alman, I got confused at the very first line that he passed an empty object into jQuery function. Also, he uses bind function object just to apply it in that nearly “empty” object (I used firebug to examine that object and it just return an jQuery object contain empty object inside). Could someone explain this logic for me?
Thank sooo much!
P/S: I understand the usage and the idea behind Pub/Sub pattern in non-framework context, just don’t understand its implementation in jQuery.
Here is the code of library I’ve read:
(function($){
var o = $({});
$.subscribe = function() {
o.bind.apply( o, arguments );
};
$.unsubscribe = function() {
o.unbind.apply( o, arguments );
};
$.publish = function() {
o.trigger.apply( o, arguments );
};
})(jQuery);
WHen you create a jQuery object of an element… final object includes all the jQuery methods
Over simplified example:
The empty object in the demo code is used to be able to do the same thing. Once it is wrapped in
$()it can have jQuery event handlers bound to it as the object includes many of the jQuery methods( not all) as propertiesYou could write:
And in another part of code