2011-04-26 114 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) 

    }); 
};