I know $() is the jQuery function… but what does $({}) reference/do? I’m looking at Ben Alman’s code in https://gist.github.com/705311
(function(jQuery){
var o = jQuery({});
jQuery.each({
"subscribe" : "bind",
"unsubscribe" : "unbind",
"publish" : "trigger"
}, function ( fn, api ) {
jQuery[ fn ] = function() {
o[ api ].apply( o, arguments );
};
});
})(jQuery);
I’m trying to figure out how this code does what it does. Can someone break it down? Also, what is the jQuery.apply() method? I don’t see it in the jQuery docs – I can only find a 4 year old jQuery apply() plugin, which I doubt is in core now.
There’s a newer, less complicated version at https://gist.github.com/661855, but I’m more curious what/how the 0.X version of this code even worked.
..edit..
I realize that $({}) is an empty object wrapped in jQuery. The question is, why do it, and how does he then end up having created $.subscribe(), $.unsubscribe(), and $.publish() from this tiny snippet of code, especially the o[ api ].apply( o, arguments ); bit?
This code creates an object to use for the observer pattern. Here’s an explanation line by line:
footnote 1: see http://msdn.microsoft.com/en-us/scriptjunkie/hh201955.aspx
footnote 2: see http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx