簡體   English   中英

如何通過其原型擴展jquery插件的公共方法?

[英]How to extend a jquery plugin's public methods through its prototype?

如何擴展插件的公共方法的原型

例如,我的插件中有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);

有任何想法嗎?

我認為在這種情況下你可以做的最好的結構根本不涉及原型。 檢查這個插件庫:

(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可能更$[pluginName]

// 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

您無法將原型擴展到外部,因為您使用隱藏對象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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM