A little knowledge of Jquery plugin development

//According to the description of "jQuery Advanced Programming", there are three main ways to develop jQuery plug-ins:

//(1) Extend jQuery through $.extend()
//(2) Add new methods to jQuery via $.fn
//(3) Created by applying jQuery UI's widget factory method via $.widget()

//Usually we use the second method for simple plug-in development, which is relative to the third method.
//The third method is used to develop more advanced jQuery components. The components developed in this mode have many built-in features of jQuery.
//For example, the status information of the plug-in is automatically saved, various common methods about the plug-in, etc., are very intimate, and I won't go into details here.

//And the first way is too simple, just add a static method to the jQuery namespace or understand it as jQuery.
//So when we call the function added via $.extend()
// Called directly by the $ symbol ($.myfunction())
// without selecting the DOM element ($('#example').myfunction()). See the example below.

$.extend({
    sayHello:function(name){
        console.log('Hello,' + (name ? name : 'Dude') + '!');
    }
});

$.extend({
   log:function(message){
       var now = new Date(),
           y = now.getFullYear(),
           m = now.getMonth() + 1,// The month in jquery starts from 0
           d = now.getDay(),
           h = now.getHours(),
           m = now.getMinutes();
           s = now.getSeconds(),
           time = y + '/' + m + '/' + d + '/' + h + ':' + m + ':' + s;
           console.log(time + ' My App: ' + message);
   }
});


$.fn.myPlugin = function(options){
    var defaults = {
            'color':'red',
            'fontSize':'12px'
    };
    // When passing more than one parameter to the extend method, it will merge all parameter objects into the first one.
    //At the same time, if there is an attribute with the same name in the object, the latter will overwrite the former when merging.
    //Using this, we can define an object in the plugin that holds the default values ​​of the plugin parameters,
    //At the same time, merge the received parameter object into the default object,
    //Finally, the parameter with the user-specified value uses the specified value,
    // Unspecified parameters use plugin defaults.
    
   // var settings = $.extend(defaults,options);
    
    //A good practice is to pass a new empty object as the first parameter of $.extend,
    //defaults and the parameter object passed by the user follow,
    // The advantage of this is that all values ​​are merged onto this empty object, protecting the default values ​​in the plugin.
    var settings = $.extend({},defaults, options);
    
    return this.css({
        'color':settings.color,
        'fontSize':settings.fontSize
    });
};

//Object-oriented plugin development

//Define the constructor of Beautifier
var Beautifier = function(ele,opt){
    this.$element = ele,
    this.defaults = {
            'color':'red',
            'fontSize':'12px',
            'textDecoration': 'none'
    },
    this.options = $.extend({},defaults,opt);
};
//Define the method of Beautifier
Beautifier.prototype = {
        beautify:function(){
            return this.$ellement.css({
                'color':this.options.color,
                'fontSize':this.options.fontSize,
                'textDecoration': this.options.textDecoration
            });
        }
};
//Use the Beautifier object in the plugin
$.fn.beautifyPlugin = function(options){
    var beautifier = new Beautifier(this,options);
    return beautifier.beautify();
};

// A good practice is to always wrap your code with self-invoking anonymous functions,
// This way you can safely use it anywhere with complete peace of mind, with absolutely no conflicts.
//We know that we can't easily create scopes with curly braces in JavaScript,
//But functions can form a scope, and the code in the scope cannot be accessed by the outside world.
// If we put our own code into a function, it won't pollute the global namespace,
//At the same time, it will not conflict with other code.
;(function($, window, document,undefined) {
    //Define the constructor of Beautifier
    var Beautifier = function(ele, opt) {
        this.$element = ele,
        this.defaults = {
            'color': 'red',
            'fontSize': '12px',
            'textDecoration': 'none'
        },
        this.options = $.extend({}, this.defaults, opt);
    };
    //Define the method of Beautifier
    Beautifier.prototype = {
        beautify: function() {
            return this.$element.css({
                'color': this.options.color,
                'fontSize': this.options.fontSize,
                'textDecoration': this.options.textDecoration
            });
        }
    };
    //Use the Beautifier object in the plugin
    $.fn.myPlugin = function(options) {
        //Create an entity of Beautifier
        var beautifier = new Beautifier(this, options);
        // call its method
        return beautifier.beautify();
    };
})(jQuery, window, document);

//About variable definition and naming

//Now let's talk about the naming of variables and methods. There are no hard and fast rules, but in order to be standardized, it is necessary to follow some conventions.

//Variable definition: A good practice is to define the variable names to be used together with a var keyword at the beginning of the code, and separate the variable names with commas. There are two reasons:

//First, it is easy to understand, know which variables will be used in the following code, at the same time, the code is clean and regular, and it is easy to manage, and the variable definition is separated from the logic code;
//The second is because all variables and function names in JavaScript will be automatically promoted, which is also called the Hoist feature of JavaScript. Even if you intersperse the definition of variables in the logic code, the declarations of these variables will still be promoted during the code parsing and running. At the top of the current scope, it is more logical for us to define variables at the beginning of a scope. Of course, again, this is just a convention, not a requirement.
//Variable and function names generally use CamelCase, that is, the first letter of the first word is lowercase, and the first letter of the following words is uppercase, such as resultArray, requestAnimationFrame.
//For constants, all letters are capitalized, and multiple words are separated by underscores, such as WIDTH=100, BRUSH_COLOR='#00ff00'.
//When the variable is of jQuery type, it is recommended to start with $, it will be uncomfortable at first, but it will be very convenient after frequent use, because it can be easily distinguished from ordinary variables,
//As soon as we see the beginning of $, we know that it is a jQuery type and can directly call jQuery related methods on it, such as var $element=$('a'); After that, it can be easily used in the code behind it, and is easily distinguishable from other variables.

//The use of quotation marks: Since these have nothing to do with the plugin theme, here is one more sentence,
//Generally, double quotes are used in HTML code, but single quotes are used in JavaScript, such as the following code:

var name = 'Wayou';
document.getElementById('example').innerHTML = '< a href="http: //wayouliu.duapp.com/">'+name+'</a>'; //href=".." keep in HTML Double quotes, keep single quotes in JavaScript

//On the one hand, double quotes are used in HTML code.
// On the other hand, when quotes are also needed within quotes in JavaScript,
//It is a legal statement to require us to write single and double quotation marks, unless you use the escape character.
//Furthermore, insisting on such unification can keep the code style consistent, and there will be no double quotes for strings here, and single quotes for other places.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326966122&siteId=291194637