jquery Plugin Development Detailed tutorial _jquery

Source: Internet
Author: User

Extending the jquery Plug-ins and methods is very powerful, and it can save a lot of development time. This article will outline the basics of jquery plug-in development, best practices, and common pitfalls.

First, Getting Started

Writing a jquery plugin starts with adding new feature attributes to Jquery.fn, where the name of the object attribute is the name of your plugin:

Copy Code code as follows:

JQuery.fn.myPlugin = function () {

Your own plug-in code

};

User very like the $ symbol where did it go? It still exists, but in order to avoid conflicts with other JavaScript libraries, we'd better pass jquery to a self executing closure program, which is mapped to $ notation in this program, which avoids the $ number being overridden by other libraries.
Copy Code code as follows:

(function ($) {
$.FN.M yplugin = function () {
Your own plug-in code
};
}) (JQuery);

In this enclosing program, we can use the $ symbol indefinitely to represent the jquery function.


Second, the environment

Now we can start writing the actual plug-in code. Before that, however, we have to have a concept of the environment in which plug-ins are in place. Within the scope of the plug-in, the This keyword represents the jquery object that the plug-in will execute, and there is a common misconception that this keyword represents the native DOM element in other jquery functions that contain callback. This often leads to developers mistakenly wrapping this keyword into jquery, as shown below.

Copy Code code as follows:

(function ($) {
$.FN.M yplugin = function () {

It is not necessary here to include this in the $ number (this), as this is already a jquery object.
$ (this) equals $ ($ (' #element '));

This.fadein (' normal ', function () {

Here the This keyword in the callback function represents a DOM element

});

};
}) (JQuery);

$ (' #element '). Myplugin ();


III. Basic Knowledge

Now that we understand the basics of the jquery plug-in, let's write a plugin to do something.

Copy Code code as follows:

(function ($) {

$.FN.M axheight = function () {

var max = 0;

This.each (function () {
max = Math.max (max, $ (this). Height ());
});

return Max;
};
}) (JQuery);

var tallest = $ (' div '). MaxHeight (); Returns the height of a DIV element with the highest height

This is a simple plugin that uses. Height () to return the height of the highest-height div element in the page.

Iv. Maintenance of Chainability

Many times, the intent of a plug-in is simply to modify the collected elements in some way and pass them on to the next method in the chain. This is the beauty of jquery's design and is one of the reasons why jquery is so popular. Therefore, to keep a plugin chainability, you must make sure that your plugin returns this keyword.

Copy Code code as follows:

(function ($) {

$.fn.lockdimensions = function (type) {

Return This.each (function () {

var $this = $ (this);

if (!type | | | type = = ' width ') {
$this. Width ($this. width ());
}

if (!type | | type = = ' height ') {
$this. Height ($this. Height ());
}

});

};
}) (JQuery);

$ (' div '). Lockdimensions (' width '). CSS (' Color ', ' red ');

Because the plugin returns the This keyword, it remains chainability so that the jquery-collected elements can continue to be controlled by jquery methods such as. css. Therefore, if your plugin does not return intrinsic value, you should always return the This keyword within its scope. In addition, you may infer that the parameters passed to the plug-in will be passed within the scope of the plug-in. Therefore, in the preceding example, the string ' width ' becomes the type parameter of the plug-in.

V. Default values and Options

For more complex and customizable plug-ins that offer many options, it is best to have a default setting that can be extended when plug-ins are invoked (by using $.extend). So, instead of calling a plugin with a lot of parameters, you can call an object parameter that contains the settings you want to overwrite.

Copy Code code as follows:

(function ($) {

$.fn.tooltip = function (options) {

Create default values that extend any of the provided options
var settings = $.extend ({
' Location ': ' Top ',
' Background-color ': ' Blue '
}, Options);

Return This.each (function () {

ToolTip Plug-in Code

});

};
}) (JQuery);

$ (' div '). tooltip ({
' Location ': ' Left '
});

In this example, when the ToolTip plug-in is invoked, the location option in the default setting is overridden, and the Background-color option remains the default, so the set value that is eventually invoked is:

Copy Code code as follows:

{
' Location ': ' Left ',
' Background-color ': ' Blue '
}

This is a flexible way to provide a highly configurable plug-in without the developer having to define all available options.


Six, the name space

Correct namespace your plug-in is a very important part of plug-in development. The right namespace ensures that your plugin will have a very low chance of being overwritten by other plug-ins or other code on the same page. Namespaces also make your life easier as a plugin developer, because it can help you better track your methods, events, and data.

Vii. Plug-in Methods

In any case, a separate plug-in should not have more than one namespace in the JQuery.fnjQuery.fn object.

Copy Code code as follows:

(function ($) {

$.fn.tooltip = function (options) {
This
};
$.fn.tooltipshow = function () {
Is
};
$.fn.tooltiphide = function () {
Bad
};
$.fn.tooltipupdate = function (content) {
// !!!
};

}) (JQuery);

This is not encouraged because it $.fn to make $.fn namespace confusing. To solve this problem, you should collect all the plug-in methods in the object text by passing the string name of the method to the plug-in to invoke them.
Copy Code code as follows:

(function ($) {

var methods = {
Init:function (options) {
This
},
Show:function () {
Is
},
Hide:function () {
Good
},
Update:function (content) {
// !!!
}
};

$.fn.tooltip = function (method) {

Method calls
if (Methods[method]) {
Return methods[method].apply (this, Array.prototype.slice.call (arguments, 1));
else if (typeof method = = = ' object ' | |!method) {
Return methods.init.apply (this, arguments);
} else {
$.error (' method ' + method + ' does not exist on Jquery.tooltip ');
}

};

}) (JQuery);

Calling the Init method
$ (' div '). tooltip ();

Calling the Init method
$ (' div '). tooltip ({
Foo: ' Bar '
});

Calling the Hide method
$ (' div '). ToolTip (' hide ');

Calling the Update method
$ (' div '). ToolTip (' Update ', ' This is the new ToolTip content! ');

This type of plug-in architecture allows you to encapsulate all the methods in the parent package by passing the string name of the method and the additional parameters required by this method to invoke them. The encapsulation and architectural type of this approach is the standard for the jquery plug-in community, which is used by countless plug-ins, including plug-ins and widgets in jQueryUI.

VIII. Events

The function of a little known bind method is to allow the binding of event namespaces. If your plug-in binds an event, a good practice is to give this event namespace.   In this way, you do not interfere with other types of events that may have been bound when you unbind them. You can add namespaces to the events you need to bind through ' .<namespace> '.

Copy Code code as follows:

(function ($) {

var methods = {
Init:function (options) {

Return This.each (function () {
$ (window). bind (' Resize.tooltip ', methods.reposition);
});

},
Destroy:function () {

Return This.each (function () {
$ (window). Unbind ('. ToolTip ');
})

},
Reposition:function () {
//...
},
Show:function () {
//...
},
Hide:function () {
//...
},
Update:function (content) {
//...
}
};

$.fn.tooltip = function (method) {

if (Methods[method]) {
Return methods[method].apply (this, Array.prototype.slice.call (arguments, 1));
else if (typeof method = = = ' object ' | |!method) {
Return methods.init.apply (this, arguments);
} else {
$.error (' method ' + method + ' does not exist on Jquery.tooltip ');
}
};

}) (JQuery);

$ (' #fun '). ToolTip ();
After some time ...
$ (' #fun '). ToolTip (' Destroy ');

In this example, when ToolTip is initialized through the Init method, it binds the reposition method to the Resize event and assigns the namespace to the reposition method by appending. ToolTip. Later, when the developer needs to destroy the ToolTip, we can unbind the reposition method and the resize event at the same time by passing the reposition namespace to the plugin. This allows us to safely unbind the event and will not affect bindings outside of this plug-in.

Ix. data

Typically, when a plugin is developed, you may need to record or check whether your plugin has been initialized to an element. The data method using jquery is a good way to log variables based on elements. Still, it's a better way to use a separate object to save all variables than to record separate data for a large number of different names, and to read the object through a separate namespace.

Copy Code code as follows:

(function ($) {

var methods = {
Init:function (options) {

Return This.each (function () {

var $this = $ (this),
data = $this. Data (' tooltip '),
tooltip = $ (' <div/> ', {
Text: $this. attr (' title ')
});

If the plugin hasn ' t been initialized yet
if (!data) {

/*
Do more setup stuff here
*/

$ (this). Data (' tooltip ', {
Target: $this,
Tooltip:tooltip
});

}
});
},
Destroy:function () {

Return This.each (function () {

var $this = $ (this),
data = $this. Data (' tooltip ');

Namespacing FTW
$ (window). Unbind ('. ToolTip ');
Data.tooltip.remove ();
$this. Removedata (' tooltip ');

})

},
Reposition:function () {
// ...
},
Show:function () {
// ...
},
Hide:function () {
// ...
},
Update:function (content) {
// ...
}
};

$.fn.tooltip = function (method) {

if (Methods[method]) {
Return methods[method].apply (this, Array.prototype.slice.call (arguments, 1));
else if (typeof method = = = ' object ' | |!method) {
Return methods.init.apply (this, arguments);
} else {
$.error (' method ' + method + ' does not exist on Jquery.tooltip ');
}

};

}) (JQuery);

Encapsulating data through namespaces in one object makes it easier to read the properties of all plug-ins from one set of locations.

X. Summary and best practices

Writing jquery Plug-ins allows you to make libraries that integrate the most useful functionality into reusable code, saving developers time and making development more efficient. When developing jquery plug-ins, keep in mind:

1. Always wrap in a closed plugin:

Copy Code code as follows:
(function ($) {
* Plugin goes here * *
}) (JQuery);

2. Do not redundant package this keyword is within the functionality of the plugin
3. Unless the plug-in returns a specific value, the This keyword is always returned to maintain chainability.
4. Pass an extensible default object parameter instead of a large number of parameters to the plug-in.
5. Do not name different methods multiple times in a plugin.
3. Always namespace methods, events, and data.

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.