2014-09-28 52 views
0

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

回答

2

handleCancelhandleAccept功能不被初始化。因此,当您设置对话框的默认值时,它们是未定义的。

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

$.fn.dialog(); 
1

尝试重新安排片内的块,增加一个过滤器,以防止两者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>