如何通过其原型扩展jQuery插件的公共方法?

3

如何扩展插件的 原型 中的公共方法?

例如,我有一个插件中的 method1 方法,并且我想通过其 .prototype 添加另一个或更多方法。这是否可行?

var extensionMethods = {
   method2: function(){
        return this;
    }
};

$.fn.MyPlugin.prototype = extensionMethods;

console.log($(".element").MyPlugin());

结果,
 Object { Element={...}, Options={...}, method1=function()}

理想情况下,
 Object { Element={...}, Options={...}, method1=function(), method2=function(), method2function()}

我的插件样板文件

(function ($) {

    // Create the plugin name and defaults once
    var pluginName = 'MyPlugin';

    // Attach the plugin to jQuery namespace.
    $.fn[pluginName] = function(PublicOptions) {

        // Set private defaults.
        var Defaults = {
            param1:       'param1',
            param2:       'param2',
            onSuccess:    function(){}
        };

        // Do a deep copy of the options.
        var Options = $.extend(true, {}, Defaults, PublicOptions);

        // Define a functional object to hold the api.
        var PluginApi = function(Element, Options) {
            this.Element   = Element;
            this.Options   = Options;
        };

        // Define the public api and its public methods.
        PluginApi.prototype = {

            method1: function(PublicOptions) {

                // Process the options.
                var Options = $.extend(true, {}, this.Options, PublicOptions);
                return this.Options;
            }
        };

        //Create a new object of api.
        return new PluginApi(this, Options);
    };

})(jQuery);

有什么想法吗?

根据你的结构(非常不幸,因为这不是jQuery插件),你只能通过一些返回$(".element").MyPlugin()对象来访问PluginApi.prototype,因为PluginApi构造函数是在IIFE内部定义的。但这当然不是很好的做法。 - dfsq
我该如何更改结构以允许这样做? - Run
这里有各种好的链接 http://jqueryboilerplate.com/ 无论使用什么模式,请注意从插件本身返回的内容。 - charlietfl
谢谢。我以前用过一些这样的模式,但我发现$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );不太好。 - Run
1
它将所有插件代码包装起来并隔离它(闭包),同时为 $ 提供上下文,因此插件不会在其他使用 $ 的页面上中断。 - charlietfl
显示剩余7条评论
2个回答

2

我认为在这种情况下,你可以采用最佳结构,而不需要涉及原型。请检查此插件基础:

(function($) {

   // Set private defaults.
    var Defaults = {
        param1: 'param1',
        param2: 'param2',
        onSuccess: function() {}
    };

    // Define the public api and its public methods.
    var PluginApi = {

        extend: function(name, method) {
            PluginApi[name] = method;
            return this;
        },

        init: function(PublicOptions) {

            // Do a deep copy of the options.
            var Options = $.extend(true, {}, Defaults, PublicOptions);

            return this.each(function() {
                console.log('set up plugin logic', this.tagName);
            });
        },

        method1: function() {
            console.log('called: method1');
            return this;
        }
    };

    // Create the plugin name and defaults once
    var pluginName = 'MyPlugin';

    // Attach the plugin to jQuery namespace.
    $.fn[pluginName] = function(method) {

        if (PluginApi[method]) {
            return PluginApi[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } 
        else if (typeof method === 'object' || !method) {
            return PluginApi.init.apply(this, arguments);
        } 
        else {
            $.error('Method ' + method + 'does not exist');
        }
    };

})(jQuery);

这个插件结构允许您像期望的那样链接方法:

$('h1').MyPlugin('method1').css('color', 'red');

如果需要使用不存在的方法,你可以这样做:

// Extend plugin "prototype" with method2 and use it
$('h1, h2').MyPlugin('extend', 'method2', function(prop, value) {
    return this.css(prop, value);
}).MyPlugin('method2', 'color', 'green');

请查看下面的演示中的用法示例。

(function($) {

   // Set private defaults.
    var Defaults = {
        param1: 'param1',
        param2: 'param2',
        onSuccess: function() {}
    };

    // Define the public api and its public methods.
    var PluginApi = {

        extend: function(name, method) {
            PluginApi[name] = method;
            return this;
        },

        init: function(PublicOptions) {
            
            // Do a deep copy of the options.
            var Options = $.extend(true, {}, Defaults, PublicOptions);
            
            return this.each(function() {
                console.log('set up plugin logic', this.tagName);
            });
        },

        method1: function() {
            console.log('called: method1');
            return this;
        }
    };

    // Create the plugin name and defaults once
    var pluginName = 'MyPlugin';

    // Attach the plugin to jQuery namespace.
    $.fn[pluginName] = function(method) {

        if (PluginApi[method]) {
            return PluginApi[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } 
        else if (typeof method === 'object' || !method) {
            return PluginApi.init.apply(this, arguments);
        } 
        else {
            $.error('Method ' + method + 'does not exist');
        }
    };

})(jQuery);


// Call existen method1: should make h1 and h2 red
$('h1, h2').MyPlugin('method1').css('color', 'red');

// Call non-existent method2: should throw error in console
try {
    $('h1, h2').MyPlugin('method2').css('color', 'green');
}
catch (e) {
  // Extend "plugin" prototype with method2
  $('h1, h2').MyPlugin('extend', 'method2', function(prop, value) {
      return this.css(prop, value);
  }).MyPlugin('method2', 'color', 'green');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>H1</h1>
<h2>H2</h2>

或者更优化的方法是在$[pluginName]命名空间中定义一个静态方法extend:

// Attach the plugin to jQuery namespace.
$.fn[pluginName] = function(method) {

    if (PluginApi[method]) {
        return PluginApi[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } 
    else if (typeof method === 'object' || !method) {
        return PluginApi.init.apply(this, arguments);
    } 
    else {
        $.error('Method ' + method + 'does not exist');
    }
};

$[pluginName] = {};
$[pluginName].extend = function(name, method) {
    PluginApi[name] = method;
};

然后在需要添加额外方法时,可以像这样使用它:

$.MyPlugin.extend('method2', function(prop, value) {
    return this.css(prop, value);
});

$('h1, h2').MyPlugin('method2', 'color', 'green');

最终演示:http://plnkr.co/edit/qqlfRqAM84goscU5BFNU?p=preview


谢谢你的编辑。我可以问一下.call(arguments, 1);是什么意思吗?为什么参数中有1 - Run
1
它将arguments集合转换为参数数组,但是不包括第一个参数。请查看 slice 方法。 - dfsq

1
你无法在外部扩展原型,因为你使用了隐藏的对象PluginApi。 你可以尝试将PluginApi存储到插件函数之外:
$[pluginName] = function(Element, Options) {
    this.Element   = Element;
    this.Options   = Options;
};
$[pluginName].prototype = {
    method1: function(PublicOptions) {
        // Process the options.
        var Options = $.extend(true, {}, this.Options, PublicOptions);
        return this.Options;
    }
};

$.fn[pluginName] = function(PublicOptions) {
    // Set private defaults.
    var Defaults = {
        param1:       'param1',
        param2:       'param2',
        onSuccess:    function(){}
    };

    // Do a deep copy of the options.
    var Options = $.extend(true, {}, Defaults, PublicOptions);

    return new $[pluginName](this, Options);
};

然后你可以扩展原型:
$.MyPlugin.prototype.method2 = function() {
    return this;
}

谢谢你的回答。我能问一下如何在不依赖$(jQuery)的情况下实现$[pluginName] = function(Element, Options) {}吗?或者根本不可能吗? - Run
1
@tealou 我已经将 PluginApi 存储在 $ 中,这样你就可以在外部访问它了。将 staff 存储在 $ .pluginName 中是一个好习惯。如果你不想将其存储在 $ 中,则可以使用 window.MyPlugin。 - jcubic
明白了。我觉得使用window是更好的选择。我不太喜欢过于依赖jQuery。对于基本结构来说,减少对它的依赖越好! - Run

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接