10 tips to help you create a better jquery plugin _jquery

Source: Internet
Author: User
Tags class definition closure

This article summarizes the 10 tips to help you create a better jquery plugin. Share to everyone for your reference. The details are as follows:

After developing a lot of jquery plug-ins, I slowly worked out a set of architecture and patterns that developed a comparison standard for jquery plug-ins. So I can copy & paste most of the code structure, just focus on the most important logical code on the line. Using the same design pattern and architecture also makes it easier to fix bugs or two of times. A validated architecture ensures that my plugin is not a big problem, whether it's simple or complex. I am here to share 10 lessons I have summed up.

1. Put all your code in the closure

This is the one I use the most. But sometimes the method outside the closure can not be invoked.

However, your plug-in code is only for your own plug-in services, so there is no problem, you can put all the code in the closure.

And the method should probably be placed inside the prototype method.

(function ($) {  
  //code here 
}) (JQuery);

2. Provide default options for Plug-ins

Your plugin should have some options that can be set by the developer, so it is necessary to provide a restore default option. You can set these options by using the Extend feature of jquery:

var defaultsettings = {   mode      : ' Pencil ',   
               linewidthmin  : ' 0 ',   
               linewidthmax  : ' Ten '   
               , LineWidth    : ' 2 '}; 
Settings = $.extend ({}, DefaultSettings, Settings | | {});

3. Use to return an element

A good feature of Javascript/jquery is that it is possible to cascade methods, so we should not break this feature and always return an element in the method. I follow this in every one of my jquery plug-ins.

$.fn.wpaint = function (settings) {return  
 This.each (function () { 
    var elem = $ (this);    
  Run some code here   
 } 
}

4. One-time code is placed outside the main loop

This one is important, but it is often overlooked. Simply put, if you have a piece of code that is a bunch of defaults, you just have to instantiate it once instead of every time you invoke your plug-in function, you should put this code outside the plug-in method. This will allow your plug-in to run more efficiently and save memory.

var defaultsettings = {  
               mode      : ' Pencil ',   
               linewidthmin  : ' 0 ',   
               linewidthmax  : ' Ten '   
               , LineWidth    : ' 2 '}; 
Settings = $.extend ({}, DefaultSettings, Settings | | {});
$.fn.wpaint = function (settings) {return  
 This.each (function () { 
    var elem = $ (this);    
  Run some code here   
 } 
}

You can note that the "DefaultSettings" in the above code is completely outside the plug-in method, because the code is in the closure, we don't have to worry about these variables being rewritten.

5. Why to set Class prototyping

As the blood and flesh 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 can create these methods without repeating them.

Reference a ready-made method to the proportion of new create a good fast much.

To put it simply, prototype is an extension of an object, providing it with a method rather than instantiating the methods in each object. This also makes your code more organized and efficient. Once you get used to this type of development, you'll find that it saves you a lot of time in your future projects.

6. How to set Class prototyping

There are two parts to set up a prototype method. First we need to create our original class definition, which in most cases means creating an object. This definition contains a different part of each object instance. In my paint jQuery Plugin plugin, I wrote this:

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

Here's how to add a global approach:

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

The key here is to make the prototype method generic, but the data is per instance itself and can be referenced with "this".

7. Use the "this" object

By using the $this, we can pass the correct reference to another closure. We may also need to pass $this references to other methods. It should be noted that $this this name can be changed, arbitrary variable names can be.

Canvas.prototype = {  
 generate:function ()  { 
    //some code    
  var $this = this;    
  var Buton =//...some code  
    button.click (function () {//using This'll not being 
    found since it has it ' s own    
    this Use $this instead.     
   $this. SomeFunc ($this);}  
 , 
 somefunc:function ($this)   {  
    //won ' t know what ' this '.  
   Use $this instead passed from the Click event  
  } 
}

8. Save settings in each object

I keep my settings in each object and then manipulate its own settings. So you don't have to pass a lot of parameters in different ways. Placing these variables in the object also makes it easier for you to call these variables elsewhere.

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

9. Detach your prototype method logic

This may be a basic principle. When you hesitate to provide a way, you can ask yourself "if someone else is going to rewrite this method, will your code meet his needs?" Or "How hard is it for someone else to write this?" This is, of course, a matter of flexibility. Here's a list of my color Picker jQuery Plugin, which you can refer to:

Generate () 
appendcolors () colorselect () Colorhoveron () 
colorhoveroff 
() appendtoelement () 
Showpalette () 
Hidepalette ()

10. Provide setter/getter option

This one is not necessary, but I find all my plugins are in this one. Because it only needs a little bit of code, it can provide someone with the functionality he might need.

Basically, we just allow developers to set or get the values that an element already exists:

var linewidth = $ ("#container"). Wpaint ("LineWidth"); 
$ ("#container"). Wpaint ("LineWidth", "5");

Summary: The above 10 basically covers the core of jquery plug-in development and can be developed as a template. A basic set of code can greatly shorten your development time and allow you to be more confident in designing your plug-in architecture.

I hope this article will help you with your jquery programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.