从 jQuery 插件内部访问公共函数

Accessing public functions from inside a jQuery plugin

本文关键字:函数 访问 内部 jQuery 插件      更新时间:2023-09-26

这是我第一次在没有教程的情况下编写jQuery插件。现在(2014年9月28日(,jQuery网站不起作用(我不知道为什么(,所以我在那里找不到任何资源。

以下是我的插件报告错误的一部分:

$(function($){
    $.fn.dialog = function(command, options) {
        var opts = $.extend( {}, $.fn.dialog.defaults, options );
        //code
        $.fn.dialog.handleCancel = function() {
        };
        $.fn.dialog.handleAccept = function() {
        };
        return this;
    };
    $.fn.dialog.defaults = {
        // some other props
        onCancel: $.fn.dialog.handleCancel(),
        onAccept: $.fn.dialog.handleAccept()
    };
    // code
}(jQuery));

当我调用插件($("#dialog1").dialog(/*..*/)(时,浏览器控制台显示以下内容:

Uncaught TypeError: undefined is not a function

错误与onCancel: $.fn.dialog.handleCancel()

.

如何访问这些方法,它们应该在哪里?(我还希望他们可以访问对话框本身的$(this) <-(

调用 $.fn.dialog 函数之前,不会初始化handleCancel函数和handleAccept函数。 因此,当您设置对话框默认值时,它们是未定义的。

$.fn.dialog.defaults之前插入此代码:

$.fn.dialog();

尝试在块内重新排列块,添加一个过滤器,以防止默认情况下同时调用handleCancelhandleAccept; 例如,

(function($){
    $.fn.dialog = function(command, options) {
      var $el = this;
        // access , pass arguments to methods
        $.fn.dialog.handleCancel = function(c) {
          $el.html(c + "led")
        };
        $.fn.dialog.handleAccept = function(a) {
          $el.html(a + "ed")
        };
        // call `handleCancel` or `handleAccept` ,
        // based on `command`
        $.fn.dialog.defaults = {
        // some other props
        onCancel: command === "cancel" 
                              ? $.fn.dialog.handleCancel(command) 
                              : null,
        onAccept: command === "accept" 
                              ? $.fn.dialog.handleAccept(command) 
                              : null
    };
        var opts = $.extend( {}, $.fn.dialog.defaults, options );
        //code
        
        return this;
    };
    // code
}(jQuery));
$("button").on("click", function(e) {
  $("#result").dialog(e.target.id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="accept">accept</button><button id="cancel">cancel</button><br />
Result: <div id="result"></div>