2011-10-11 53 views
4

我試圖在jQuery插件中使用.proxy()方法。不知道發生了什麼,但它不會調用methods.strobe。我已經得到了下面的示例代碼:使用.proxy調用插件方法()

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

我有這個的jsfiddle來進行測試:http://jsfiddle.net/CZqFW/

任何投入,將不勝感激。

回答

6

jQuery proxy()返回一個函數,該函數使用第二個參數的上下文關閉第一個參數。

你可以調用返回的函數,它會立即執行。

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

這提供給您的唯一的事情就是更換this上下文methods.strobe()的。您可以使用JavaScript的call()函數來完成同樣的事情:

methods.strobe.call(this); 

你的jQuery插件已成立strobe()作爲$ .fn.notify的方法。所以,你可以這樣調用它太:

this.notify('strobe'); 
+0

真棒邁克,也許我應該仔細看看文檔中的例子!非常感謝:) – matt

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

返回調用strobe方法,但總是難免this新的功能。它實際上並沒有調用scrobe函數。所以,你需要做的是實際調用該功能:

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

謝謝輸入toby,我不得不接受麥克的答案,因爲他擊敗了你的拳頭。謝謝你倆的明確答案:) – matt

相關問題