I’m trying to use the .proxy() method in a jquery plugin. Not sure what’s going on but it’s not calling methods.strobe. I’ve got the following sample code:
(function($) {
var settings = {
}
var methods = {
init: function(options) {
alert('init fired');
$.proxy(methods.strobe,this);
return this;
},
destroy: function() {
},
strobe: function(){
alert('strobe fired');
},
show: function() {},
hide: function() {},
refresh: function() {}
};
$.fn.notify = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.notify');
}
};
})(jQuery);
$().notify();
I’ve got this jsfiddle for testing: http://jsfiddle.net/CZqFW/
Any input would be appreciated.
jQuery proxy()returns a function that closes the first parameter with the context from the second.You can call the returned function and it will execute immediately.
The only thing this provides to you is replacement of the
thiscontext formethods.strobe(). You can use javascript’scall()function to accomplish the same thing:Your jQuery plug-in has set up
strobe()as a method on $.fn.notify. So you can call it like this too: