10 tips to create a better jquery plugin

Source: Internet
Author: User

Preface: after developing a lot of jquery plug-ins, I slowly developed a set of jquery plug-ins to develop a comparative standard structure and patterns. So I can copy & paste most of the code structure, just focus on the most important logic code on the line. Using the same design pattern and architecture also makes it easier to fix bugs or develop two of times. A validated architecture ensures that my plugins are not a big problem, whether the plugin is 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 most I have used. But sometimes the method outside the closure cannot be called.
However, your plugin code is only for your own plug-in service, so there is no problem, you can put all the code in the closure.
The method may be placed inside the Prototype method.

(function ($) {
code here
}) (jQuery);

2. Provide default options for plugins

Your plugin should have some options that are available for developers to set up, so providing a restore default option is necessary. 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 the ability to cascade methods, so we should not break this feature and always return an element in the method. I follow this rule in every jQuery plugin I have.

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

4. One-time code outside the main loop

This one is important, but it is often overlooked. To put it simply, if you have a piece of code that is a bunch of default values, you just have to instantiate it once, instead of instantiating it every time you call your plug-in function, 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: ' Ten ',
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 code above is completely outside the plugin method, since the code is inside the closure, we don't have to worry about these variables being rewritten.

5. Why to set Class prototyping

As your code of blood and Flesh, 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.

Referencing an out-of-the-box method to create a new one is much faster.

Simply put,prototype is an extension of an object that provides methods to it without instantiating them 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 the Class prototyping

There are two parts to setting 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 each instance of its own and can be referenced with "this" .

7. Use the "this" object

By using "$this", we can pass the correct reference to another closure. We may also need to pass $this references to other methods. It is important to note that the name of the $this can be changed

, any of the variable names can be.

Canvas.prototype = {
generate:function () {
//some Code
var $this = this;
var Buton =//...some Code
Button.Click (function () {
//using This is not being 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 the settings in each of the objects

I always save my settings in each object and then manipulate its own settings. So you don't have to pass a lot of arguments in different ways. Putting these variables in the object also makes it easy for you to call these variables elsewhere.


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

9. Separating your prototype method logic

This may be a basic principle. When you hesitate to provide a way, you can ask yourself, "If someone else wants to rewrite this method, will your code meet his needs?" Or "how difficult is it for someone else to write this method?" Of course, this is a matter of flexibility. Here is a list of my Color picker jQuery Plugin methods, you can refer to:

Generate ()
Appendcolors ()
ColorSelect ()
Colorhoveron ()
Colorhoveroff ()
Appendtoelement ()
Showpalette ()
Hidepalette ()

10. Setter/getter Options available

This one is not necessary, but I found all my plugins are in this one. Because it only requires a little bit of code, it can provide someone with a function that he might need.

Basically, we just have to let the developer set or get the value that the element already exists:

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

Summary: The above 10 articles basically cover the core of jquery plug-in development, and can be used as a development template. A set of basic code can greatly shorten your development time, and will allow you to design the plug-in architecture more confident.

10 tips to create a better jquery plugin

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.