如何在另一个插件调用的设置中存储插件方法调用而不在jQuery中执行它?

时间:2018-05-18 09:30:22

标签: javascript jquery function methods

我有两个jquery插件。让我们将它们称为插件A和插件B.我想将插件B中的方法分配给插件A的一个设置。我的问题是pluginA.settings.action中的方法在HTML中定义后立即执行。

<button>Click Me!</button>
<div id="message"></div>
$('button').pluginA({
  action: $('#message').pluginB("btnAction")
});

如果在插件A的设置中定义方法而没有实际调用方法,我怎么能这样做?

(function($) {
    $.fn.pluginA = function(method) {
        var $element;
        var methods = {
            init : function(options) {
                settings = $.extend({}, this.pluginA.defaults, options);
                return this.each(function() {
                    $element = $(this);
                    element = this;
                  $element.on('click', function(){
                    settings.action;
                  })
                })
            }
        }
        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 in pluginA plugin!');
        }

    }

    $.fn.pluginA.defaults = {  
            ajaxUrl: "http://wordpress.com",
            eventId: 0,
            element: null
    }

    $.fn.pluginA.settings = {}

    $.fn.pluginB = function(method) {
        var $element;
        var methods = {
            init : function(options) {
                settings = $.extend({}, this.pluginB.defaults, options);
                return this.each(function() {
                    $element = $(this);
                    element = this;
                })
            },
            btnAction: function(){
                $element.text('The button was clicked!');
            }
        }
        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 in pluginB plugin!');
        }

    }

    $.fn.pluginB.defaults = {  
            ajaxUrl: "http://wordpress.com",
            eventId: 0,
            element: null
    }

    $.fn.pluginB.settings = {}

})(jQuery);

0 个答案:

没有答案