matt
matt

Reputation: 320

Call to plugin method using .proxy()

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.

Upvotes: 4

Views: 2679

Answers (2)

airportyh
airportyh

Reputation: 22668

$.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 that function:

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

Upvotes: 4

Mike Haboustak
Mike Haboustak

Reputation: 2296

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');

Upvotes: 6

Related Questions