Calling the plugin method using .proxy ()

I am trying to use the .proxy () method in a jquery plugin. Not sure what is going on, but it does not call methods. I have the following code example:

(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 have this jsfiddle for testing: http://jsfiddle.net/CZqFW/

Any input would be appreciated.

+4
source share
2 answers

jQuery proxy() returns a function that closes the first parameter with context from the second.

You can call the returned function and execute it immediately.

 $.proxy(methods.strobe,this)(); 

The only thing you are given is the replacement of the this context for methods.strobe() . You can use the javascript call() function to accomplish the same thing:

 methods.strobe.call(this); 

The jQuery plugin configured strobe() as a method in $ .fn.notify. Therefore, you can call it this:

 this.notify('strobe'); 
+6
source
 $.proxy(methods.strobe,this); 

returns a new function that calls the strobe method, but always bound to this . It does not actually call the scrobe function. So what you need to do is actually call this function:

 var strobe = $.proxy(methods.strobe,this); strobe(); 
+4
source

All Articles