jQuery experience and suggestions

Posted by Boudga on Tue, 28 Dec 2021 06:13:04 +0100

After developing many jQuery plug-ins, I slowly found out a set of standard structures and patterns for developing jQuery plug-ins. So I can copy and paste most of the code structure, just focus on the main logical code. Using the same design pattern and architecture also makes it easier to fix bug s or secondary development. A proven architecture can ensure that my plug-in does not have major problems, whether it is simple or complex. Here I share 10 lessons I have learned.

1. Put all your code in the closure

This is the one I use most. But sometimes methods outside closures cannot be called. However, the code of your plug-in only serves your own plug-in, so there is no problem. You can put all the code in the closure. The method may be placed inside the Prototype method, which we will talk about later.

/* He asked about hovertree com */
(function($)   
 {   
 //code here   
 })(jQuery);   

2. Provide default options for plug-ins

Your plug-in should have some options that developers can set, so it is necessary to provide the option to restore the default. You can set these options through the extend function of jQuery:

/* He asked about hovertree com */
var defaultSettings = {   
   mode            : 'Pencil',   
   lineWidthMin    : '0',   
   lineWidthMax    : '10',   
   lineWidth       : '2'  
};   
    
settings = $.extend({}, defaultSettings, settings || {});   

3. Use to return an element

A good feature of JavaScript/jQuery is that it can cascade methods, so we should not break this feature and always return an element in the method. I follow this in every jQuery plug-in I have.

$.fn.wPaint = function(settings)   
  {   
    return this.each(function()   
    {   
        var elem = $(this);   
    
        //run some code here com
    }   
}   

4. The one-time code is placed outside the main loop

This one is very important, but it is often ignored. In short, if you have a piece of code that is a pile of default values and only needs to be instantiated once, instead of instantiating every time you call your plug-in function, you should put this piece of code outside the plug-in method. This can make your plug-in run more efficiently and save memory. We will look at the application of this method in practice when we discuss prototype later.

var defaultSettings = {   
    mode            : 'Pencil',   
    lineWidthMin    : '0',   
    lineWidthMax    : '10',   
    lineWidth       : '2'  
};   
    
$.fn.wPaint = function(settings)   
{   
    settings = $.extend({}, defaultSettings, settings || {});   
    
    return this.each(function()   
    {   
        var elem = $(this);   
    
        //run some code here com 
     }   
}   

You can notice that the "defaultSettings" in the above code is completely outside the plug-in method. Since these codes are in closures, we don't have to worry about rewriting these variables.

5. Why set Class Prototyping

As the blood and flesh of your code, methods and functions should be placed in the prototype function. There are two reasons:

▲ it can save a lot of memory because you don't have to create these methods repeatedly.

▲ referencing an existing method is much better and faster than re creating one.

In short, prototype extends an object and provides methods for it without instantiating these methods in each object. It also makes your code more organized and efficient. Once you get used to this development method, you will find that it will save you a lot of time in your future projects.

6. How to set Class Prototyping

Setting up a prototype method has two parts. First, we need to create our original class definition, which in most cases means creating an object. This definition contains different parts of each object instance. In my Paint jQuery Plugin, I wrote:

/* He asked about hovertree com */
function Canvas(settings)   
{   
    this.settings = settings;   
    this.draw = false;   
    this.canvas = null;         
    this.ctx = null;   
    
    return this;   
}   

To add a global method:

/* He asked about hovertree com */
Canvas.prototype =   
{   
  generate: function()   
 {   
        //generate code   
  }   
}   

The key here is to make the prototype method universal, but the data is each instance's own and can be referenced with "this".

7. Use the "this" object

By using "this", we can pass the correct reference to other closures. We may also need to pass this reference to another method. It should be noted that,

Canvas.prototype =   
{   
    generate: function()   
    {   
        //some code   
    
        var $this = this;   
    
        var buton = //...some code   
    
       button.click(function(){   
            //using this will not be found since it has it's own this   
    
            //use $this instead.   
    
           $this.someFunc($this);   
        });   
    },   
    
    someFunc: function($this)   
    {   
        //won't know what "this" is.   
        //use $this instead passed from the click event   
    }   
}   /* He asked about hovertree com */

8. Save settings in each object

I always save my own settings in each object, and then manipulate its own settings. So you don't have to pass many parameters in different methods. Putting these variables in an object also makes it easy for you to call them elsewhere.

function Canvas(settings)   
{   
    this.settings = settings;   
    
    return this;   
}   
/* He asked about hovertree com */

9. Separate your Prototype method logic

This may be a basic principle. When you are hesitant to provide a method, you can ask yourself, "if someone else wants to rewrite this method, will your code meet his needs?" Or "how difficult is it for others to write this method?". Of course, this is a question of flexibility. The methods of my Color Picker jQuery Plugin are listed here. You can refer to:

generate()   
appendColors()   
colorSelect()   
colorHoverOn()   
colorHoverOff()   
appendToElement()   
showPalette()   
hidePalette()   

10. Provide Setter/Getter options

This one is not necessary, but I found that all my plug-ins use this one. Because it only needs a little code, it can provide others with a function they may need.

Basically, we just let developers set or get the existing value of the element:

1 2

var lineWidth = $( "#container" ).wPaint( "lineWidth" ); $( "#container" ).wPaint( "lineWidth" , "5" );

First we associate the element with the object, and then we can reference it. We do the following before returning the element:

return this.each(function()   
{   
    var elem = $(this);   
    
   var canvas = new Canvas(settings);   
    
    //run some code here   
    
   elem.data("_wPaint_canvas", canvas);   
}   
//The following code defines what we really want to do:   
$.fn.wPaint = function(option, settings)   
{   
   if(typeof option === 'object')   
    {   
        settings = option;   
    }   
    else if(typeof option === 'string')   
    {   
        if(   
            this.data('_wPaint_canvas') &&   
            defaultSettings[option] !== undefined   
        ){   
            var canvas = this.data('_wPaint_canvas');   
    
            if(settings)   
            {   
                canvas.settings[option] = settings;   
              return true;   
            }   
            else  
            {   
                return canvas.settings[option];   
           }   
        }   
        else  
            return false;   
    }   
    
    return this.each(function()   
    {   
        //run some code here   
    }   
}   /* He asked about hovertree com */

The above ten articles basically cover the core of jQuery plug-in development, and can be used as a development template. Having a basic set of code can greatly shorten your development time and make you more confident in designing plug-in architecture.

recommend: http://www.cnblogs.com/roucheng/p/texiao.html

Publisher: full stack programmer, stack length, please indicate the source for Reprint: https://javaforall.cn/120410.html Original link: https://javaforall.cn