开发者

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;

     开发者_Python百科   },
        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');


$.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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜