Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 645
matt Avatar asked Dec 27 '22 12:12

matt


1 Answers

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');
like image 148
Mike Haboustak Avatar answered Jan 17 '23 12:01

Mike Haboustak