如何基于这个jQuery插件模式向jQuery插件添加公共方法

时间:2014-06-12 15:04:32

标签: javascript jquery jquery-plugins

如何将公共方法添加到我的自定义jQuery插件中,该插件基于 jquery-boilerplate 中的此模式: https://github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.extend-skeleton.js

我需要使用我的插件并调用这样的公共方法:

jQuery('.element').pluginName();

//And now assuming that plugin has a public method `examplePublicMethod`,
//I want to call it like this:
var instance = jQuery('#element').data('pluginName');
instance.examplePublicMethod();

当我从链接中使用此模式时,它是否可能?以下是此模式的代码示例:

;(function($){
    $.fn.extend({
        pluginName: function( options ) {

            this.defaultOptions = {};

            var settings = $.extend({}, this.defaultOptions, options);

            return this.each(function() {

                var $this = $(this);
                //And here is the main code of the plugin
                //...
                //And I'm not sure how to add here a public method
                //that will be accessible from outside the plugin

            });

        }

    });

})(jQuery);

1 个答案:

答案 0 :(得分:7)

有多种方法可以做到这一点,但我喜欢的是:

$.fn.extend({
    pluginName: function( options ) {

        this.defaultOptions = {};

        var settings = $.extend({}, this.defaultOptions, options);

        return this.each(function() {

            var $this = $(this);

            //Create a new Object in the data.
            $this.data('pluginName', new pluginMethods($this)) //pluginMethod are define below

        });

    }

});

function pluginMethods($el){
    //Keep reference to the jQuery element
    this.$el = $el; 
    //You can define all variable shared between functions here with the keyword `this`
}

$.extend(pluginMethods.prototype, {
    //Here all you methods
    redFont : function(){
        //Simply changing the font color
        this.$el.css('color', 'red')
    }
})


$('#el').pluginName();

//Public method:
var instance = jQuery('#el').data('pluginName');
instance.redFont();

缺点是每个人都可以访问pluginMethods。但是你可以通过在插件声明的相同闭包中移动它来解决这个问题:

(function($){
    $.fn.extend({
        pluginName: function( options ) {

            this.defaultOptions = {};

            var settings = $.extend({}, this.defaultOptions, options);

            return this.each(function() {

                var $this = $(this);

                $this.data('pluginName', new pluginMethods($this))

            });

        }

    });

    function pluginMethods($el){
        //Keep reference to the jQuery element
        this.$el = $el; 
    }

    $.extend(pluginMethods.prototype, {
        //Here all you methods
        redFont : function(){
            this.$el.css('color', 'red')
        }
    })

})(jQuery);