JQuery plug-in Development (from juqery official website)

Source: Internet
Author: User
Document directory
  • 6.1 method)
  • 6.2 Event)
  • 6.3 data)

I did not pay attention to some methods and techniques for encapsulating plug-ins when I wrote js in the past. Now I want to translate the jquery document, while I am studying it myself, I also want to give me a little bit of spiritual food for cainiao like me ~ Kiss ~

I. Start

To write a plug-in, add a function object named after you to the jquery. fn object.

jQuery.fn.myPlugin = function() {
// code
};

If you want to use the $ symbol that we are familiar with and do not want it to conflict with other script libraries

(function( $ ) {
$.fn.myPlugin = function() {
// code
};
})( jQuery );

Now we can use the dollar symbol to replace the troublesome "jQuery ".

Ii. Background

Now we can start to develop our own plug-ins, but before that, we must note that within the scope of the plug-in function we have compiled, this keyword indicates the jquery object that calls the plug-in.

This is a common error, because in the callback function of jquery, The this keyword often represents a DOM element, which leads to excessive encapsulation of this keyword.

(Function ($ ){
$. Fn. myPlugin = function (){

// You do not need to write $ (this) because this is already a jquery object.

// $ (This) means $ ('# element '));

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

// Here this represents a DOM Element

});
};
}) (JQuery );
$('#element').myPlugin();
3. Basic Knowledge

Now we understand the background of the jquery plug-in. Now let's write a small demo to see how the plug-in is implemented.

(function( $ ){
$.fn.maxHeight = function() {

var max = 0;

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

return max;
};
})( jQuery );
Var tallest = $ ('div '). maxHeight (); // return the height of the highest div

This is a simple example.

4. Link persistence

In the preceding example, the height of a div is returned, but the plug-in is usually used to modify the elements of the set and pass the elements to the next method for execution through the link.

To maintain connectivity, make sure that our plug-in returns 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');

.

Therefore, if your plug-in does not return an inherent value, you should return this keyword in the scope of your plug-in function.

In addition, as you think, the parameters you pass to your plug-in call obtain the scope of your plug-in function (okay... I admit that this sentence cannot be translated... It probably means that the passed parameters are available in the scope, nonsense @_@~!).

In the previous example, the string 'width' is changed to the 'type' parameter in the plug-in function '.

5. Default Value (defaults) and configuration (options)

Many options are provided for more complex and configurable plug-ins. When the plug-in is called, it is the best to have scalable default settings (with $. extend.

Therefore, instead of calling a plug-in with a large number of parameters, it is better to call this plug-in with only one parameter, but this parameter is an object that can be rewritten.

Here is an example of how to implement

(Function ($ ){
$. Fn. tooltip = function (options ){

// Create some default values and use the options provided for extension
Var settings = $. extend ({
'Location': 'top ',
'Background-color': 'blue'
}, Options );

Return this. each (function (){
// Code
});
};
}) (JQuery );
$('div').tooltip({
'location' : 'left'
});

In this example, after the tooltip plug-in is called with the given options, the default location is reset to 'left', while the background-color is the default 'blue '.

Therefore, the final settings object should be:

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

This is a great way to provide a highly configurable plug-in that does not require developers to define all valid options.

Vi. namespace)

Proper namespace is a very important part for plug-in development.

Correct namespace ensures that your plug-in is only a small one that may be overwritten by other plug-ins or code on the same page.

Namespace makes your life easier as a plug-in developer because it helps you better track your methods, events, and data.

6.1 method)

In any case, a separate plug-in requires more than one namespace in the jquery. fn object.

(function( $ ){

$.fn.tooltip = function( options ) {
// THIS
};
$.fn.tooltipShow = function( ) {
// IS
};
$.fn.tooltipHide = function( ) {
// BAD
};
$.fn.tooltipUpdate = function( content ) {
// !!!
};

})( jQuery );

This is not good because it makes the jquery. fn namespace messy.

To solve this problem, you should collect methods in all your plug-ins into an object and call them by passing the name string of this 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 calling logic
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 );

// calls the init method
$('div').tooltip();

// calls the init method
$('div').tooltip({
foo : 'bar'
});
// calls the hide method
$('div').tooltip('hide');
// calls the update method
$('div').tooltip('update', 'This is the new tooltip content!');

This type of plug-in architecture allows you to encapsulate all your methods in the parent closed plug-in (parent scope ?) And pass in the method name string to call them, and then pass in the required parameters for these methods.

In the jquery plugin community, the encapsulation and structure of such methods are a standard, which is used by countless plug-ins, including jqueryUI plug-ins and components.

6.2 Event)

A little-known binding method features the ability to name methods already bound. If your plug-in is bound to an event, a good way is to name it (that is, to call it by passing the event name string through the namespace method in the example ?!)

In this way, if you want to unbind (unbind) in the future, you can exclude interference from other events that may be bound to the same event type.

You can name your events by appending ". <namespace>" to the method of the event type you bind.

(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();
// Some time later...
$('#fun').tooltip('destroy');

In this example, when the tooltip is initialized by the init method, it binds the reposition Method to the resize event of the window in the "tooltip" namespace.

Then, if the developer needs to destroy the tooltip, we can pass in its name to the unbind method to unbind the plug-in event (unbind). In this example, it is "tooltip ".

This allows us to safely unbind events and eliminate unexpected unbinding events outside the plug-in.

6.3 data)

During plug-in development, if your plug-in has initialized a given element, you need to maintain it or check it.

Using jquery's data method is a great way to keep track of the variables of each basic element.

However, it is best to use an object to hold all your variables and access this object using a separate data name, instead of keeping track of a bunch of scattered 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 plug-in has been initialized
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 );

Data helps you track variables and statuses in your plug-in methods. Name your data to an object, so that you can easily access all attributes of your plug-in from a central location, and easily cancel the name of the data you want to remove.

VII. Summary and best practices

Writing jquery plug-ins can make use of efficient libraries and abstract the most flexible and useful functions, making them reusable code, saving you time and making your development more efficient.

The following is a simple summary, which should be kept in mind during the next development of the jquery plug-in:

1. Always put your plug-in a closure:

(function( $ ){ /* plugin goes here */ })( jQuery );

2. Do not reencapsulate this keyword in the scope of your plug-in function

3. Unless your plug-in returns a fixed value, the plug-in always returns the this keyword to maintain continuity.

4. Instead of using a large number of parameters, you should pass your settings into an object that can extend the default value of your plug-in.

5. Do not make a plug-in have more than one namespace, resulting in confusion of the jquery. fn object.

6. Always name your 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.