Introduction to jQuery plug-in development

Preface

jQuery plug-in development includes two types:

  1. Adding static methods to jQuery

  2. Adding methods to jQuery prototypes

Adding static methods to jQuery

  1. Add new global functions 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, they can be invoked in the plug-in, so that the plug-in javascript can be directly referenced without calling again.

Adding methods to jQuery prototypes

This is the most common method in plug-in development.

The simplest form

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

context

In the immediate scope of the plug-in function, the keyword this points to the jQuery object that invokes the plug-in, and does not need to be wrapped in $again.

(function($){
    $.fn.pluginName = function() {      
        // There's no need to write $(this) because "this" is a jQuery object             
    };          
})(jQuery);

Keep Chain Call

To keep the chain call, please return this for the plug-in.

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 allows users to modify default parameters either by passing parameters or by modifying $.fn.pluginName.defaults

Exposing 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);

In this way, users can either call a public function or modify it.

Safer Closure Writing

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

Add ";" in order to prevent the error caused by the code without ";" before the plug-in, and add that windows and document are such that system variables such as windows have a local reference inside the plug-in, which can improve access speed, and can also compress these variables internally. undefined is to prevent others from modifying undefined quotes by mistake. Send plug-in bug s.

More

The following is from netizens Blog

(function () {   
    var Plugin,
        privateMethod;  //Private methods for plug-ins
     
    /**
     * Here is a self-running singleton pattern.
     * 
     */
    Plugin = (function () {
 
        /**
         * Instantiation of plug-ins, where the code invoked during initialization can be placed
         */
        function Plugin(element, options) {
            //Merge the default parameters and user-defined parameters of the plug-in into a new obj
            this.settings = $.extend({}, $.fn.plugin.defaults, options);
            //Assigning dom jquery object to plug-in to facilitate subsequent calls
            this.$element = $(element);
             
        }
 
        /**
         * A common method of a plug-in, equivalent to an interface function, for external calls
         */
        Plugin.prototype.doSomething = function () {
            /**
             * Method content
             */
        };
         
        return Plugin;
 
    })();
 
    /**
     * Private methods for plug-ins
     */
    privateMethod = function () {
     
    };
 
    /**
     * Here's the key
     * Define a plugin
     */
    $.fn.plugin = function (options) {
        var instance;
        instance = this.data('plugin');
        /**
         *Determine whether the plug-in has been instantiated or returns the instantiated object directly if it has been instantiated
         */
        if (!instance) {
            return this.each(function () {
                //Cache instantiated plug-ins in the dom structure (in memory)
                return $(this).data('plugin', new Plugin(this, options));
            });
        }
        if (options === true) return instance;
        /**
         * Elegance: If the plug-in's parameter is a string, the plug-in's string method is called.
         * For example, $(' id').plugin('doSomething') is actually called $(' id).plugin.doSomething();
         * doSomething It's the interface just defined.
         * This approach is common in juqery ui plug-ins.
         */
        if ($.type(options) === 'string') instance[options]();
        return this;
    };
     
    /**
     * Default values for plug-ins
     */
    $.fn.plugin.defaults = {
        property1: 'value',
        property2: 'value'
    };
 
    /**
     * Elegance: Instantiate plug-ins through data-xxx.
     * In this way, no calls need to be displayed on the page.
     */
    $(function () {
        return new Plugin($('[data-plugin]'));
    });   
}).call(this);

Reference resources

A Plugin Development Pattern

Keywords: Javascript JQuery Windows

Added by dragonfly4 on Wed, 17 Jul 2019 01:08:31 +0300