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.
$.proxy(methods.strobe,this)();
The only thing this provides to you is replacement of the this
context for methods.strobe()
. You can use javascript's call()
function to accomplish the same thing:
methods.strobe.call(this);
Your jQuery plug-in has set up strobe()
as a method on $.fn.notify. So you can call it like this too:
this.notify('strobe');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With