Implementation of plug-in based on jquery

Keywords: Javascript JQuery

To facilitate user creation of plug-ins, jquery provides jQuery.extend() and jQuery.fn.extend() methods

1.jQuery.extend() method has an overload.

jQuery.extend(object), a parameter used to extend the jQuery class itself, that is, to add new functions on the jQuery class / namespace, or called static methods, such as the built-in ajax methods of jQuery are called with jQuery.ajax(), which is a bit like the static method of "class name. method name". Let's also write an example of jQuery.extend(object).

      //extend jQuery Object itself
        jQuery.extend({
            "minValue": function (a, b) {
                ///<summary>
                /// Compare two values to return the minimum
                ///</summary>
                return a < b ? a : b;
            },
            "maxValue": function (a, b) {
                ///<summary>
                /// Compare the two values to return the maximum
                ///</summary>
                return a > b ? a : b;
            }
        });
        //call
        var i = 100; j = 101;
        var min_v = $.minValue(i, j); // min_v Equal to 100
        var max_v = $.maxValue(i, j); // max_v Equal to 101

Overloaded version: jQuery.extend([deep],target,object1,[objectN])

For one or more other objects to extend an object and return the extended object.
If no target is specified, the jQuery namespace itself is extended. This helps plug-in authors add new methods to jQuery.  
If the first parameter is set to true, jQuery returns a deep copy, recursively copying any object found. Otherwise, the copy will share the structure with the original object.  
Undefined attributes will not be copied, however, attributes inherited from the prototype of the object will be copied.
parameter
deep: Optional. If set to true, merge recursively.
target: Object to be modified.
object1: Object to be merged into the first object.
objectN: Optional. Objects to be merged into the first object.

Example 1:

/*Merge settings and options, modify and return settings.*/
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);

console.log(settings) //validate: true | limit: 5| name: "bar"

Example two:

/*Merge defaults and options without modifying defaults.*/
var empty = {};
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = jQuery.extend(empty, defaults, options);

console.log(settings); //validate: true, limit: 5, name: "bar" 
console.log(empty); //validate: true, limit: 5, name: "bar"

2.jQuery.fn.extend(object) extends the set of jQuery elements to provide new methods (usually used to make plug-ins).

Looking at the jQuery code, you can see the original jQuery.fn = jQuery.prototype, which is the prototype of the jQuery object. The jQuery.fn.extend() method is the prototype method for extending jQuery objects. We know that extending the method on the prototype is equivalent to adding "member method" to the object, and "member method" of the class "requires the object of the class to be invoked, so using the method of jQuery.fn.extend(object), an instance of the jQuery class can use this"member function". jQuery.fn.extend(object) and jQuery.extend(object) methods must be distinguished.

3. Encapsulate a complete jQuery plug-in below

html:

<p> I am a little bird!! </p>

js:

(function($) {
                $.fn.extend({
                    "highLight": function(options) {
                        //Check whether the parameters passed in by users are legitimate
                        if(!isValid(options))
                            return this;
                        var opts = $.extend({}, defaluts, options); //Use jQuery.extend Override plug-in default parameters
                        return this.each(function() { //There this Namely jQuery Object. Here return To support chain invocation
                            //Travel through all to be highlighted dom,When called highLight()Plug-ins are a collection of times.
                            var $this = $(this); //Get current dom Of jQuery Object, here's this It's the current cycle. dom
                            //Setting according to parameters dom Style
                            $this.css({
                                backgroundColor: opts.background,
                                color: opts.foreground
                            });
                            //Format highlighted text
                            var markup = $this.html();
                            markup = $.fn.highLight.format(markup);
                            $this.html(markup);
                        });

                    }
                });
                //Default parameters
                var defaluts = {
                    foreground: 'red',
                    background: 'yellow'
                };
                //Common Formatting Method. The default is bold. Users can achieve different formatting effects by overwriting this method.
                $.fn.highLight.format = function(str) {
                    return "<strong>" + str + "</strong>";
                }
                //Private method to check whether the parameters are legitimate
                function isValid(options) {
                    return !options || (options && typeof options === "object") ? true : false;
                }
            })(window.jQuery);

            //call
            //Caller overrides common methods exposed by plug-ins
            $.fn.highLight.format = function(txt) {
                return "<em>" + txt + "</em>"
            }
            $(function() {
                $("p").highLight({ foreground: 'orange', background: '#ccc' }); //Call the custom highlight plug-in
            });

Plug-in effect:

Posted by pointsplat on Sun, 21 Apr 2019 19:36:35 -0700