Jquery plug-in development methods

Source: Internet
Author: User

First, jQuery plug-in development includes two types: one is class-level plug-in development, that is, adding a new global function to jQuery is equivalent to adding a method to the jQuery class itself. JQuery's global functions belong to the jQuery namespace. The other is object-level plug-in development, that is, adding methods to jQuery objects. The following describes the development methods of the two plug-ins.

1. Class-level plug-in development

The most direct understanding of class-level plug-in development is to add class methods to the jQuery class, which can be understood as adding static methods. A typical example is the $. AJAX () function, which is defined in the namespace of jQuery. The following extensions can be used for class-level plug-in development:

1.1 Add a new global function

To add a global function, we only need to define it as follows:

jQuery.foo=function(){alert('This is only a test.');};

1.2 add multiple global functions

Add multiple global functions, which can be defined as follows:

jQuery.foo=function(){ alert('This is only a test.');};jQuery.bar=function(param){ alert('This function takes a parameter, which is "'+param+'".');};

The call time is the same as some methods that call Jquery itself, such as jQuery. foo (); jQuery. bar (); or $. foo (); $. bar ('bar ');

1.3 Use jQuery. extend (object );

jQuery.extend({  foo:function(){  alert('This is only a test.'); },    bar:function(param){  alert('This function takes a parameter, which is "'+param +'".'); }   });

1.4 Use a namespace

Although a large number of javaScript function names and variable names are not allowed in the jQuery namespace. But it is still inevitable that some functions or variables will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into another custom namespace.

jQuery.myPlugin={      foo:function(){      alert('This is only a test.');     },        bar:function(param){      alert('This function takes a parameter, which is "'+param+'".');}       };

The namespace function is still a global function. The Calling method is $. myPlugin. foo (); or $. myPlugin. bar ('baz ');

With this technique (using an independent plug-in name), we can avoid conflicts between functions in the namespace.

2. Object-level plug-in development

There are two methods to develop object-level plug-ins:

Method 1:

(function($){ $.fn.extend({ pluginName:function(opt,callback){   // Our plugin implementation code goes here.     }   }) })(jQuery);

Method 2:

(function($){   $.fn.pluginName=function(){  // Our plugin implementation code goes here.   };})(jQuery); 

The above defines a jQuery function with the form parameter $. After the function definition is complete, pass the jQuery real parameter in. Call and execute now. The advantage is that when writing the jQuery plug-in, we can also use the $ alias instead of conflicting with the class library like prototype.

2.1 declare a name in the JQuery namespace

This is a single plug-in script. If your script contains multiple plug-ins or plug-ins that are mutually inverse (for example, $. fn. doSomething () and $. fn. undoSomething (), you need to declare multiple function names. However, when writing a plug-in, we usually try to use only one name to include all its content.

The following example shows how to name the plug-in "highlight".

$.fn.hilight=function(){  // Our plugin implementation code goes here.  };

Our plug-in can be called in this form: $ ('# myDiv'). hilight ();

But what if we need to break down our implementation code into multiple functions? There are many reasons: design needs; this is easier to maintain or understand; and this is more in line with object-oriented. This is really a headache. It breaks down the function implementation into multiple functions without adding additional namespaces.

To realize that and use functions are the most basic class objects in javascript, we can do this. Like other objects, functions can be specified as attributes. Therefore, we have declared "hilight" as a jQuery attribute object. Any other attribute or function that we need to expose can be declared in the "hilight" function. Continue later.

2.2 accept parameters to control the actions of the plug-in

During the development of the plug-in, we can pass corresponding parameters to the plug-in function to make our plug-in more flexible. For example:

$.fn.hilight=function(options){var defaults={foreground:'red',background:'yellow'};var opts=$.extend(defaults, options);// Our plugin implementation code goes here.  };

Then we can call our plug-in the following form:

$('#myDiv').hilight({foreground:'blue'  });

2.3 default settings of the exposure plug-in

We should make some improvements to the above Code to expose the default settings of the plug-in. This makes it easier for plug-in users to overwrite and modify plug-ins with less code. Next we start to use function objects.

$.fn.hilight=function(options){var opts=$.extend({}, $.fn.hilight.defaults, options);// Our plugin implementation code goes here.  };// plugin defaults - added as a property on our plugin function  $.fn.hilight.defaults={foreground:'red',background:'yellow'};

Now users can include a line of code like the following in their scripts (this only needs to be called once, and does not have to be called in the ready block ):

$. Fn. hilight. defaults. foreground = 'blue ';
Next we can use the plug-in method like this. The result is the same as that in section 2.2: $ ('# myDiv'). hilight ();

As you can see, we allow users to write a line of code in the default foreground of the plug-in. You can also overwrite these new default values as needed:

// Overwrite the Default background color of the plug-in $. fn. hilight. defaults. foreground = 'blue'; // use a new default setting to call the plug-in $ ('. hilightDiv '). hilight (); // pass the configuration parameter to the plug-in method to overwrite the default setting $ ('# green '). hilight ({foreground: 'green '});

2.4 properly expose some functions

This section will expand your plug-ins step by step through interesting methods for the previous Code Section (while allowing others to expand your plug-ins ). For example, we can define a function named "format" in the implementation of the plug-in to format the highlighted text. Our plug-in now looks like this. The implementation of the default format method is under the hiligth function.

$.fn.hilight=function(options){// iterate and reformat each matched element  return this.each(function(){var $this=$(this);// ...  var markup=$this.html();// call our format function  markup=$.fn.hilight.format(markup);$this.html(markup);});};$.fn.hilight.format=function(txt){return '<strong>'+txt+'</strong>';};

We can easily support other attributes in the options object by allowing a callback function to overwrite the default settings. This is another great way to modify your plug-in. The trick shown here is to further effectively expose the format function so that it can be redefined. With this technique, others can pass their own settings to overwrite your plug-ins. In other words, others can also write plug-ins for your plug-ins.

2.5 keep private functions

This technique exposes some of your plug-ins to be overwritten. But you need to think carefully about what is exposed in your implementation. Once exposed, you need to maintain any changes to the parameters or semantics in your mind may undermine backward compatibility. A general principle is that if you are not sure whether to expose a specific function, you may not need to do that.

So how can we define more functions without disrupting namespaces or exposing implementations? This is the function of the closure. For demonstration, we will add another "debug" function to our plug-in. This debug function will output the selected element format to the firebug console. To create a closure, we define the entire plug-in as a function.

(function($){  $.fn.hilight=function(options){    debug(this);    // ...    };  function debug($obj){    if(window.console&&window.console.log)window.console.log('hilight selection count:'+$obj.size());  };//  ...  })(jQuery);

Our "debug" method cannot enter from external closures, so our implementation is private.

2.6 Integration

The complete code after the example is completed is as follows:

// Create a closure (function ($) {// plug-in definition $. fn. hilight = function (options) {debug (this); // build main options before element iterationvar opts = $. extend ({}, $. fn. hilight. defaults, options); // iterate and reformat each matched elementreturn this. each (function () {$ this = $ (this); // build element specific optionsvar o = $. meta? $. Extend ({}, opts, $ this. data (): opts; // update element styles+this.css ({backgroundColor: o. background, color: o. foreground}); var markup00000000this.html (); // call our format function syntax (markup0000000000000000this.html (markup) ;}; // Private function: debuggingfunction debug ($ obj) {if (window. console & window. console. log) window. console. log ('hilight selection count: '+ $ obj. size () ;}; // defines the exposure format function $. fn. hilight. format = function (txt) {return '<strong>' + txt + '</strong>';}; // defaults $ of the plug-in. fn. hilight. defaults = {foreground: 'red', background: 'yellow'}; // closure end}) (jQuery );

This design allows me to create a powerful compliant plug-in. I hope it can also be done for you.

3. Summary

JQuery provides two methods for development plug-ins:

JQuery. fn. extend (object); add a method to the jQuery object.

JQuery. extend (object); adds a new method to the class to extend the jQuery class itself.

3.1 jQuery. fn. extend (object );

What is fn. It is not difficult to see jQuery code.

jQuery.fn=jQuery.prototype={init:function(selector, context){//......   }};

The original jQuery. fn = jQuery. prototype, prototype is certainly no stranger. Although javascript does not have a clear concept of a class, it is more convenient to use a class to understand it.

JQuery is a well-encapsulated class. For example, we use the statement $ ("# btn1") to generate a jQuery class instance.

JQuery. fn. extend (object); Extension of jQuery. prototype is to add "member functions" to the jQuery class ". JQuery class instances can use this "member function ".

For example, we want to develop a plug-in and create a Special edit box. When it is clicked, the content in the current edit box of alert is displayed. You can do this:

$.fn.extend({     alertWhileClick:function(){         $(this).click(function(){              alert($(this).val());         });     }});

$ ("# Input1"). alertWhileClick (); // <input id = "input1" type = "text"/>

$ ("# Input1") is a jQuery instance. When it calls the member method alertWhileClick, the extension is implemented. When it is clicked, the content in the current edit is displayed.

3.2 jQuery. extend (object );

Add a class method to the jQuery class, which can be understood as adding a static method. For example:

$.extend({add:function(a,b){return a+b;}});

Add a "static method" for jQuery as add, and then you can use this method at the place where jQuery is introduced. $. add (3, 4); // return 7

Articles you may be interested in
  • Php smarty Chinese interception plug-in development example
  • Jquery pop-up window plug-in (compatible with all browsers)
  • Js shields mouse and keyboard events (including right-click, direction key, backspace key, F5 refresh key, etc.), compatible with IE and firefox
  • How to Prevent event bubbling in JQuery and Its Differences
  • Jquery QQ emoticons
  • Examples of using Google map for javascript development roadmap
  • JQuery-handle the latency of a hover event
  • Ii. Principle: II. Principle in software development

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.