jquery plug-in writing related technical design summary and best practices

Source: Internet
Author: User

Original: http://www.itzhai.com/ JQUERY-PLUG-IN-THE-PREPARATION-OF-RELATED-TECHNICAL-DESIGN-SUMMARY-AND-BEST-PRACTICES.HTML1, declaring plug-in name:

Add a function to the Jquery.fn (Jquery.prototype) object, and the name of the function is your plug-in name:

function () {  //Do your awesome plugin stuff here};

In cases where naming does not conflict with other jquery functions, you can use the $ symbol in a closed package:

(function ($) {  function () {    //Do your awesome plugin stuff here  };}) (jQuery);  
2, the context of the plugin:

jquery receives a callback, which itself points to the DOM, and uses this directly to the equivalent of our usual $ (this) situation:

(function ($) {  function () {    //There ' s no need to does $ (this) because    //"This" is already a J Query Object    //$ (this) would is the same as $ ($ (' #element '));    This.fadein (//The This keyword is a DOM element});}) (jQuery); $ (' #element '). Myplugin ();       

Here is a simple jquery plugin that implements the maximum height for all div:

(function ($) {  function () {    var max = 0;    This.each (function () {      max = Math.max (max, $ (return Max;};}) (JQuery); var tallest = $ (//Returns The height of the tallest div       
3, the maintenance of links:

The previous example returns a div with the highest integer value, but the usual intent is only to some extent only to modify the collection of elements of the plug-in and pass them to the method in the next chain. Such a design of jquery is elegant place. So to keep the link to a plugin, you must make sure that your plugin returns this keyword.

(Function ($) {$.fn.lockdimensions =function (type) {Returnthis.each (function () {var $this = $ (this); Span class= "Bh_code_a_js_keywords" >if (!type | | type =  ' width ') {$this.width ($this.width ());} if (!type | | type = =  ' height ') {$ This.height ($this.height ());}); };}) (jQuery); $ ( ' width '). CSS ( ' color ',  ' red ');     

Because the plug-in returns the scope of the This keyword, it maintains the link, and jquery can continue to take advantage of jquery methods such as. css. So, if your plugin does not return an intrinsic value, you should always return this.

4, the transfer of parameters, defaults and options:
(function ($) {$.fn.tooltip = function ( Options) {//Create some defaults, extending them with any options that were PR          ovided var settings = $.extend ({ ' location ' :  ' top ',  ' Background-color ': return this.each (function () {//Tooltip plugin code here}); };}) (jQuery); $ ( ' div '). tooltip ({ ' location ': Span class= "bh_code_a_js_string" > ' Left '})            

Merges default parameters and caller-passed arguments by $.extend.

5. Namespaces:

The right namespace is a very important part of plug-in development. The correct namespace ensures that your plugin will have a very low chance of being overwritten by his plugin or code on the same page.

In no case should you claim multiple namespaces in a plug-in's Jquery.fn object.

(function ($) {  function (options) {     //This  };  function () {    //Is  };  // !!! };}) (jQuery);     

You should collect all the methods into an object literal and call through the literal value of the method:

(Function ($) {var methods = {init:function (options) {This}, show:function () {is}, Hide:function () {Good}, UPDATE:function (content) {// !!! } }; $.fn.tooltip =Function (method) {Method Calling Logicif (Methods[method]) {Return methods[Method].apply (This, Array.prototype.slice.call (arguments, 1)); }Elseif (typeof method = = =' Object ' | | ! method) {Return Methods.init.apply (this, arguments); }else {$.error ( ' method ' + method +  ' does not exist on Jquery.tooltip '); } };}) (JQuery); //calls the init method$ ( ' div '). tooltip (); Span class= "bh_code_a_js_comments" >//calls the init method$ ( ' div '). ToolTip ({foo: //calls the Hide method$ ( ' div '). ToolTip ( Span class= "bh_code_a_js_string" > ' hide '); //calls the update method$ ( ' div '). ToolTip ( Span class= "bh_code_a_js_string", "Update",  ' This is the new ToolTip content! ');  

This type of method encapsulation and architecture is a standard in the jquery plug-in community, and it applies to countless plugins, including jQueryUI plugins and widgets.

6. Events:

The Bind method allows you to bind an event through a namespace, and if your plug-in binds an event, you can do so through a namespace, when unbinding an event, to prevent other events from being affected. You can set the namespace of the binding event by means of ".<namespace>".

(Function ($) {var methods = {init:function (options) {ReturnThis.each (Function () {$ (window). Bind (' Resize.tooltip ', methods.reposition); }); }, Destroy:function () {ReturnThis.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);} Span class= "Bh_code_a_js_keywords" >else {$.error ( ' method ' + method +  ' does not exist on Jquery.tooltip '); } };}) (jQuery); $ ( Some time later...$ ( ' #fun '). ToolTip ( Destroy ')               
7. Data:

The data method can refer to the official documentation: Http://docs.jquery.com/Data, which is both bound to store data in the elements of the page.

This is done by writing a plugin that allows each element in the page to be bound to some current state or content.

(Function ($) {var methods = {init:function (options) {ReturnThis.each (function () {var $This = $ (This), data = $This.data (' tooltip '), tooltip = $ (' <div/> ', {text: $This.attr (' title ')});If the plugin hasn ' t been initialized yetif (! Data) {/*Do more setup stuff here*/ $(This). Data (' tooltip ', {target: $This, tooltip:tooltip}); } }); }, Destroy:function () {ReturnThis.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.pro Totype.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);             
Summary and best practices for jquery design:

Writing a jquery plugin allows you to implement the largest class library, abstracting out the features you think are useful and reusable code that can save you time and make your development more effective. Remember when developing your next jquery plugin, you can follow a brief summary below:

1, always put your plug-in into the closure:

(/* Plugin goes here */}) (JQuery);

2, in your plug-in directly within the scope, do not add extra parcel of this keyword;

3. Unless you are returning an intrinsic value from your plugin, you will generally return the function of your plug-in to this keyword to maintain the link nature;

4, instead of passing in lengthy parameters, you should set a default parameter through your plug-in, and extend the parameters through the $.extend () method;

5. Do not use multiple namespaces in one plugin to cause Jquery.fn objects to become cluttered;

6. Always create a namespace for your methods, events, and data.

For specific plug-in development instructions, refer to the official jquery documentation:

Http://docs.jquery.com/Plugins/Authoring

jquery plug-in writing related technical design summary and best practices

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.