Home >Web Front-end >JS Tutorial >Detailed introduction to jQuery plug-in development

Detailed introduction to jQuery plug-in development

迷茫
迷茫Original
2017-03-26 16:43:301045browse

Preface

jQuery plug-in development includes two types:

  1. Add static methods to jQuery

  2. Prototype for jQuery Add method

Add static method to jQuery

  1. Add new global function directly

jQuery.foo = function() {
alert('This is a test. This is only a test.');
}

2. Use jQuery.extend(object)

jQuery.extend({
foo: function() {
alert('This is a test. This is only a test.');
},
bar: function(param) {
alert('This function takes a parameter, which is "' + param +'".');
}
});

For some globally configured plug-ins, you can call them in the plug-in, so you can directly reference the plug-in javascript without calling

to jQuery. Prototype adding method

This is the most commonly used method in plug-in development

The simplest form

(function($){       
    $.fn.pluginName = function() {     
         // code    
    };     
})(jQuery);

Context

The immediate effect of the plug-in function In the domain, the keyword this points to the jQuery object that calls the plug-in, and there is no need to wrap it with $

(function($){
    $.fn.pluginName = function() {      
        // 没有必要再写$(this),因为"this"就是jQuery对象             
    };          
})(jQuery);

Maintain chained calls

In order to maintain chained calls, the plug-in please return this.

Set default parameters and expose them

(function($){
    $.fn.pluginName = function(options) {    
        var opts = $.extend({}, $.fn.hilight.defaults, options);      
    };  

    $.fn.pluginName.defaults = {    
        foo: 'bar'   
    };                      
})(jQuery);

This way users can either pass parameters or modify the default parameters by modifying $.fn.pluginName.defaults

Expose some public functions

(function($){
    $.fn.pluginName = function(options) {    
        var opts = $.extend({}, $.fn.pluginName.defaults, options);      
    };  

    $.fn.pluginName.defaults = {    
        foo: 'bar'   
    };  

    $.fn.pluginName.foo = function() {    
        return 'bar';    
    };                  
})(jQuery);

so that users can both call public functions and modify them.

A safer way to write closures

;(function($,window,document,undefined){
    $.fn.pluginName = function() {     
         // code    
    };
})(jQuery,window,document);

Adding ";" is to prevent errors caused by the absence of ";" in the previous code of the plug-in. Adding window and document is like this. System variables such as window are in There is a local reference inside the plug-in, which can improve the access speed. At the same time, these variables can also be compressed internally. Undefined is to prevent others from accidentally modifying undefined and causing plug-in bugs.

More

The following is from a netizen’s blog

(function () {   
    var Plugin,
        privateMethod;  //插件的私有方法
     
    /**
     * 这里是一个自运行的单例模式。
     * 
     */
    Plugin = (function () {
 
        /**
         * 插件实例化部分,初始化时调用的代码可以放这里
         */
        function Plugin(element, options) {
            //将插件的默认参数及用户定义的参数合并到一个新的obj里
            this.settings = $.extend({}, $.fn.plugin.defaults, options);
            //将dom jquery对象赋值给插件,方便后续调用
            this.$element = $(element);
             
        }
 
        /**
         * 插件的公共方法,相当于接口函数,用于给外部调用
         */
        Plugin.prototype.doSomething = function () {
            /**
             * 方法内容
             */
        };
         
        return Plugin;
 
    })();
 
    /**
     * 插件的私有方法
     */
    privateMethod = function () {
     
    };
 
    /**
     * 这里是关键
     * 定义一个插件 plugin
     */
    $.fn.plugin = function (options) {
        var instance;
        instance = this.data('plugin');
        /**
         *判断插件是否已经实例化过,如果已经实例化了则直接返回该实例化对象
         */
        if (!instance) {
            return this.each(function () {
                //将实例化后的插件缓存在dom结构里(内存里)
                return $(this).data('plugin', new Plugin(this, options));
            });
        }
        if (options === true) return instance;
        /**
         * 优雅处: 如果插件的参数是一个字符串,则 调用 插件的 字符串方法。
         * 如 $('#id').plugin('doSomething') 则实际调用的是 $('#id).plugin.doSomething();
         * doSomething是刚才定义的接口。
         * 这种方法 在 juqery ui 的插件里 很常见。
         */
        if ($.type(options) === 'string') instance[options]();
        return this;
    };
     
    /**
     * 插件的默认值
     */
    $.fn.plugin.defaults = {
        property1: 'value',
        property2: 'value'
    };
 
    /**
     * 优雅处: 通过data-xxx 的方式 实例化插件。
     * 这样的话 在页面上就不需要显示调用了。
     */
    $(function () {
        return new Plugin($('[data-plugin]'));
    });   
}).call(this);

The above is the detailed content of Detailed introduction to jQuery plug-in development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn