Jquery plugin Development Guide

Source: Internet
Author: User

The extension of jquery plug-ins and methods is very powerful, which can save a lot of development time. This article provides an overview of basic jquery plug-in development knowledge, best practices, and common traps.

Directory
  • 1 entry
  • 2 Environment
  • 3 Basics
  • 4. Keep chainability
  • 5 default settings and options
  • 6. namespace
    • 6.1 plug-in method
    • 6.2 events
    • 6.3 data
  • 7. Summary and best practices
Getting started

Compile a jquery plug-in to add new function properties to jquery. FN. The name of the Object Property added here is the name of your plug-in:

Jquery. FN. myplugin = function () {// your own plug-in code };

Where do users like the $ symbol? It still exists. However, to avoid conflicts with other JavaScript libraries, we 'd better pass jquery to a self-executed closed program, where jquery maps to the $ symbol, this prevents the $ number from being overwritten by other databases.

(Function ($) {$. FN. myplugin = function () {// your own plug-in code };}) (jquery );

In this closed program, we can use the $ symbol without restrictions to represent jquery functions.

Environment

Now, we can start to write the actual plug-in code. However, before that, we must have a concept about the environment where the plug-in is located. In the scope of the plug-in, this keyword indicates the jquery object to be executed by the plug-in. This is prone to a common misunderstanding, because in other jquery functions that contain callback, this keyword represents the native DOM element. This often causes developers to mistakenly include this keyword in jquery, as shown below.

(Function ($) {$. FN. myplugin = function () {// There is no need to include this package in $ (this), because this is already a jquery object. // $ (This) is equivalent to $ ('# element'); this. fadein ('normal', funciton () {// here, the this keyword in the callback function represents a DOM element}) ;}) (jquery );
  $('#element')myPlugin();
Basic knowledge

Now we understand the basic knowledge of jquery plug-ins. Let's write a plug-in and do something.

  (function($){  $.fn.maxHeight = function(){       var max = 0;     this.each(function(){       max = Math.max(max, $(this).height());     });    return max;   }; })(jQuery);
VaR tallest = $ ('div '). maxheight (); // returns the height of the DIV element with the highest height.

This is a simple plug-in that uses. Height () to return the height of the DIV element with the highest height on the page.

Maintain chainability

Most of the time, the intention of a plug-in is to modify the collected elements in some way and pass them 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 maintain the chainability of a plug-in, you must ensure that your plug-in returns the this keyword.

  (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 chainabilityis maintained after the plug-in returns thiskey words, the elements of this jquerycollection can be continuously controlled by jquery.css. Therefore, if your plug-in does not return the inherent value, you should always return the this keyword within the scope of its function. 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 previous example, the string 'width' is changed to the type parameter of the plug-in.

Default Value and Option

For a complicated plug-in that provides many options for customization, it is best to have a default setting that can be extended when the plug-in is called (by using $. Extend ). Therefore, compared to calling a plug-in with a large number of parameters, you can call an object parameter that contains the settings you want to override.

(Function ($) {$. FN. tooltip = function (options) {// create some default values to expand any 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 called, the location option in the default settings is overwritten, and the background-color option remains the default value. Therefore, the final value to be called is:

  {   'location':'left',   'background-color':'blue' }

This is a flexible way to provide a highly configurable plug-in without the need for developers to define all available options.

Namespace

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

Plug-in method

In any case, a separate plug-in should notjQuery.fnThe jquery. FN object has multiple namespaces.

  (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$.fnConfusing the $. FN namespace. To solve this problem, you should collect the methods of all the plug-ins in the object text and call them by passing the string name of the method to the plug-in.

(Function ($) {VaR methods = {init: function (options) {// This}, show: function () {// is}, hide: function () {// good}, update: function (content ){//!!! }; $. FN. tooltip = function (method), // method call 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); // call the init method $ ('div '). tooltip (). // Call the init method $ ('div '). tooltip ({FOO: 'bar '});
// Call the hide method $ ('div '). tooltip ('hide ');
// Call the update method $ ('div '). tooltip ('update', 'This is the new tooltip content! ');

This type of plug-in architecture allows you to encapsulate all methods in the parent package and call them by passing the string name of the method and additional parameters required for this method. The encapsulation and architecture of this method are the standards of the jquery plug-in Community. It is used by countless plug-ins, including plug-ins and widgets in jqueryui.

Event

A little-known bind method allows you to bind an event namespace. If your plug-in is bound to an event, a good way is to assign the event namespace. In this way, when unbinding, you will not interfere with other events of the same type that may already be bound. You can append the namespace to the event you want to bind through '. <namespace> '.

  (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 a period of time... $ ('# Fun "). tooltip ('deststroy ').

In this example, when tooltip is initialized using the init method, it binds the reposition Method to the resize event and assigns the namespace to the non-reposition method through append. tooltip. Later, when developers need to destroy tooltip, We can unbind the reposition method from the resize event and pass the reposition namespace to the plug-in. This allows us to safely unbind events and does not affect the bindings other than this plug-in.

Data

During plug-in development, you may need to record or check whether your plug-in has been initialized to an element. Using jquery's data method is a good way to record variables based on elements. Even so, it is better to use a single object to save all variables and read the object through a separate namespace than to record a large number of separated Data with different names.

  (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 in an object through a namespace makes it easier to read the attributes of all plug-ins from a centralized location.

Summary and best practices

Writing jquery plug-ins allows you to export data and integrate the most useful functions into reusable code, saving developers time and making development more efficient. When developing jquery plug-ins, remember:

  • Always wrapped in a closed plug-in:(function( $ ){ /* plugin goes here */ })( jQuery );(Function ($) {}) (jquery );
  • Do not wrap this keyword redundant within the scope of plug-in functionality
  • Unless the plug-in returns a specific value, this keyword is always returned to maintain chainability.
  • Pass an extensible default object parameter instead of a large number of parameters to the plug-in.
  • Do not name different methods multiple times in a plug-in.
  • Always namespace methods, events, and data

Address: http://www.tripfox.com.cn/node/64

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.