2011-04-26 117 views
2

我試圖建立我的插件裏面接受一個回調函數作爲選項參數:呼叫未定義

(function($) { 

    $.fn.MyjQueryPlugin = function(options) { 
     var defaults = { 
      onEnd: function(e) {} 
     }; 

     var settings = $.extend({}, defaults, options); 

     return this.each(function() { 
      // do stuff (complete() gets called here) 

     }); 
    }; 

    function complete(e){ 
     settings.onEnd.call(this); // <- the error? 
    } 

})(jQuery); 

但我得到調用()是未定義的一個錯誤。我的代碼有什麼問題?

好吧,我改變了這個:

(function($) { 

    $.fn.MyjQueryPlugin = function(options) { 
     var defaults = { 
      onEnd: function(e) {} 
     }; 

     var settings = $.extend({}, defaults, options); 

     var complete = function(e){ 
      settings.onEnd.call(this); // <- the error? 
     } 


     return this.each(function() { 
      // do stuff (complete() gets called here) 

     }); 
    }; 

})(jQuery); 

和錯誤仍然存​​在......

+1

在你的問題中引用錯誤會很有用。 – alex 2011-04-26 08:30:15

+1

[It works for me](http://jsfiddle.net/alexdickson/pwF5k/)。 – alex 2011-04-26 08:31:37

+0

是的,這個問題出現在另一個使用call()的函數中,並且忘記改變它:D – Alex 2011-04-26 08:38:40

回答

3

您正在嘗試在其定義的函數之外引用settings。您已將作用域settings作爲您分配給$.fn.MyjQueryPlugin的函數中的局部變量,但是您將從不關閉該局部變量的函數使用它。

可以創建一個新的complete函數每次調用MyjQueryPlugin封閉在settings

(function($) { 

    $.fn.MyjQueryPlugin = function(options) { 
     var defaults = { 
      onEnd: function(e) {} 
     }; 

     var settings = $.extend({}, defaults, options); 

     return this.each(function() { 
      // do stuff (complete() gets called here) 

     }); 

     // `complete` now closes over `settings` 
     function complete(e){ 
      settings.onEnd.call(this); // <- the error? 
     } 
    }; 

})(jQuery); 

...但當然,這涉及到創建功能。也許這很好,取決於插件的功能。

或者,將settings作爲參數傳遞給complete

+1

+1 *深入* *。 – alex 2011-04-26 08:38:22

2

settings不在範圍內complete()

+0

*「你需要在你的自調用函數內部做var設置。」如果他這麼做, 'settings'將被所有對'MyjQueryPlugin'的調用所共享,這可能不是所需要的,因爲它將'options'參數混合到'settings'中。 – 2011-04-26 08:29:11

+0

@ T.J。他們應該覆蓋每次新插入的插件不是嗎? [的jsfiddle](http://jsfiddle.net/alexdickson/wk5ps/)。順便說一句,OP是*她* :) – alex 2011-04-26 08:32:39

+0

(小寫'a'):我們不知道調用不重疊(ajax,'setTimeout'等)。 @Alex(首都'A'):對不起! – 2011-04-26 08:36:03

1

變量設置超出了整個函數的範圍。將完整的功能放在您已定義設置的功能中。

$.fn.MyjQueryPlugin = function(options) { 
    var defaults = { 
     onEnd: function(e) {} 
    }; 

    function complete(e){ 
     settings.onEnd.call(this); // <- the error? 
    } 

    var settings = $.extend({}, defaults, options); 

    return this.each(function() { 
     // do stuff (complete() gets called here) 

    }); 
};