Home >Web Front-end >JS Tutorial >10 tips to help you create better jQuery plugins_jquery

10 tips to help you create better jQuery plugins_jquery

WBOY
WBOYOriginal
2016-05-16 15:58:171249browse

This article summarizes 10 suggestions to help you create better jQuery plug-ins. Share it with everyone for your reference. The specific instructions are as follows:

After developing many jQuery plug-ins, I slowly figured out a set of relatively standard structures and patterns for developing jQuery plug-ins. This way I can copy & paste most of the code structure and just focus on the main logic code. Using the same design patterns and architecture also makes it easier to fix bugs or perform secondary development. A proven architecture can ensure that my plug-ins will not cause major problems, no matter whether the plug-in is simple or complex. Here I share 10 experiences I have summarized.

1. Put all your code inside the closure

This is the one I use the most. But sometimes methods outside the closure cannot be called.

But the code of your plug-in only serves your own plug-in, so this problem does not exist. You can put all the code in the closure.

The method should probably be placed inside the Prototype method.

(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 a restore default option. You can set these options through jQuery’s extend function:

var defaultSettings = {   mode      : 'Pencil',   
               lineWidthMin  : '0',   
               lineWidthMax  : '10',   
               lineWidth    : '2' }; 
settings = $.extend({}, defaultSettings, settings || {});

3. Return an element using

JavaScript/jQuery has a good feature that it can perform method cascading, so we should not destroy this feature and always return an element in the method. I follow this rule in every jQuery plugin I create.

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

4. Place one-time code outside the main loop

This is very important, but often ignored. Simply put, if you have a piece of code that is a bunch of default values ​​and only needs to be instantiated once, rather than instantiated every time your plug-in function is called, you should put this code outside the plug-in method. This allows your plug-in to run more efficiently and save memory.

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

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

5. Why set up Class Prototyping

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

◆ It can save a lot of memory because you don’t have to create these methods repeatedly.

◆ It is much faster to reference a ready-made method than to recreate it.

Simply put, prototype extends an object and provides methods for it without instantiating these methods in every object. This also makes your code more organized and efficient. Once you get used to this way of developing, you'll find that it saves you a lot of time on your future projects.

6. How to set up Class Prototyping

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

function Canvas(settings) {  
 this.settings = settings;   
 this.draw = false;   
 this.canvas = null;    
   this.ctx = null;  
  return this;
}

Let’s add the global method:

Canvas.prototype = {   
 generate: function() { 
    //generate code  
 } 
}

The key here is to make the prototype method universal, but the data is unique to each instance 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 other methods. It should be noted that the name $this can be changed, and any variable name can be used.

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  
  } 
}

8. Save settings in each object

I've been saving my own settings in each object and then manipulating it's own settings. This way you don't have to pass many parameters in different methods. Putting these variables in an object also makes it easier for you to call these variables in other places.

function Canvas(settings) {  
 this.settings = settings;  
  return this; 
}

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 were to override this method, would your code meet their needs?" or "How difficult would it be for someone else to write this method?" ". Of course this is a question of flexibility. Here is a list of my Color Picker jQuery Plugin methods, you can refer to them:

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 include this one. Because it only requires a little bit of code to provide others with a function they may need.

Basically, we just need to allow developers to set or get the existing value of an element:

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

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

I hope this article will be helpful to everyone’s jquery programming design.

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