jquery - 如何从插件调用 jQuery 插件中的公共(public)函数

标签 jquery plugins methods call public

我正在开发一个 jQuery 插件。这是我的第一次,所以如果这是一个愚蠢的问题,我深表歉意。

我在插件中有几个公共(public)方法。

我试图从插件定义内部和插件外部调用这些方法,其方式与 Java 中方法的 public 关键字的工作方式类似,但是我不断收到 undefined is not a function 错误。

我尝试了多种方式调用它,但仍然无法让它工作。

关于如何做到这一点有什么想法吗?

这是我的代码库的示例:

$(document).ready(function() {    

    (function($) {

        // Plugin Definition
        $.fn.popup = function(options){
            // code here...

            // SUBMIT FORM
            $(settings.popupSubmitSelector).on("click", function(e) {
                submitForm();             // call to my method
                this.submitForm();
                $.fn.popup.submitForm();   
            });

            // more code here...

            // my public method
            this.submitForm = function(){
                // method code here
            }

            // more code...
        }
    }(jQuery));
});

最佳答案

我想我现在明白你的问题了。如果要在同一对象的实例中执行公共(public)方法,则必须正确引用当前实例。在 JS 中你可以这样实现:

var MyObj = function() {
  var instance = this;

  this.publicMethod = function() {
    alert('test');
  }

  var privateMethod = function() {
    instance.publicMethod();
  }

  return this;

}

更新这是使用代理函数来公开功能的插件的基本框架

(function($) {
    var settings = { ... };

    var methods = {
        init: function(options) { ... submitForm() ... },
        submitForm: function() { /* code here */ }
    };

    $.fn.popup = 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.popup');
        }
    };

})(jQuery);

然后您可以通过以下方式从外部访问

$('selector').popup('submitForm');

关于jquery - 如何从插件调用 jQuery 插件中的公共(public)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24683831/

相关文章:

java - 如何构建语法荧光笔和缩进?

php - 自定义 Post_Type 插件导致为 wp-includes/post.php 中的 foreach() 提供的参数无效

java - 从上到下编号三角形

c# - 如何使用方法实现基类并强制派生类覆盖它?

java - Eclipse Checkstyle插件(eclipse-cs)错误属性尚未设置

python - 在调用类实现的实例中调用方法 - 但在其他方面不相关

jquery - 在 css 或 jquery 中,有没有一种方法可以在 div 的边框上添加一些东西?

php - 如何正确添加一行到 Bootstrap 以修复网格系统移动到多行

javascript - 原型(prototype)模式,在 jQuery $.each 函数中使用 'this'

javascript - 到图像点击我给了一个函数,点击它就获取图像ID,使用这个我必须使用javascript更改图像