This article mainly introduces the jquery plugin development in detail tutorial that will outline the basics of jquery plug-in development, best practices and common pitfalls that need friends to refer to below
The extension of jquery plugins and methods is very powerful, it can save a lot of development time. This article outlines the basics of jquery plug-in development, best practices, and common pitfalls.
First, Getting Started
Writing a jquery plugin starts with adding to Jquery.fn?? The new feature property, the name of the object property added here is the name of your plugin:
Copy CodeThe code is as follows:
JQuery.fn.myPlugin = function () {
Your own plug-in code
};
Where did the user like the $ symbol go? It still exists, however, in order to avoid conflicts with other JavaScript libraries, we'd better pass jquery to a self-executing closed program that jquery maps to the $ symbol in this program, which avoids the $ number being covered by another library.
Copy CodeThe code is as follows:
(function ($) {
$.fn.m?? Yplugin = function () {
Your own plug-in code
};
}) (JQuery);
In this closed program, we can use the $ symbol without restrictions to represent the jquery function.
Second, the environment
Now, we can start writing the actual plug-in code. However, before that, we have to have a concept of the environment in which the plugin is located. In the scope of the plug-in, the This keyword represents the jquery object that the plugin will execute, which is prone to a common misconception, because in other jquery functions that contain callback, the This keyword represents the native DOM element. This often causes the developer to mistakenly package the This keyword in jquery, as shown below.
Copy CodeThe code is as follows:
(function ($) {
$.fn.m?? Yplugin = function () {
There is no need to have this package in the $ number as $ (this), because this is already a jquery object.
$ (this) equivalent to $ ($ (' #element '));
This.fadein (' normal ', function () {
Here the This keyword in the callback function represents a DOM element
});
};
}) (JQuery);
$ (' #element '). Myplugin ();
Third, the basic knowledge
Now that we understand the basics of the jquery plugin, let's write a plugin to do something about it.
Copy CodeThe code is 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 the highest div element
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 plugin is simply 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 one of the reasons why jquery is so popular. Therefore, to maintain the chainability of a plugin, you must make sure that your plugin returns the This keyword.
Copy CodeThe code is 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 plug-in returns the This keyword, it remains chainability so that the elements that jquery collects can continue to be controlled by jquery methods such as. css. So if your plugin doesn't 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. So, in the previous example, the string ' width ' becomes the type parameter of the plug-in.
V. Default values and Options
For more complex and customizable plugins that offer many options, it is best to have a default setting that can be extended when the plugin is called (by using $.extend). So, instead of calling a plug-in with a large number of parameters, you can call an object parameter that contains the settings you want to overwrite.
Copy CodeThe code is as follows:
(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 Plugin Code
});
};
}) (JQuery);
$ (' div '). tooltip ({
' Location ': ' Left '
});
In this example, when the ToolTip plugin is called to overwrite the location option in the default settings, the Background-color option remains the default value, so the final set value is called:
Copy CodeThe code is as follows:
{
' Location ': ' Left ',
' Background-color ': ' Blue '
}
This is a flexible way to provide a highly configurable plug-in without requiring the developer to define all available options.
Vi. namespaces
Proper namespace your plugin 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 other plugins or other code on the same page. Namespaces also make your life easier as a plugin developer, as it can help you better track your methods, events and data.
Seven, plug-in method
In any case, a separate plug-in should not have more than one namespace in the JQuery.fnjQuery.fn object.
Copy CodeThe code is 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 the $.fn namespace confusion. 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 CodeThe code is as follows:
(function ($) {
var methods = {
Init:function (options) {
This
},
Show:function () {
Is
},
Hide:function () {
Good
},
Update:function (content) {
// !!!
}
};
$.fn.tooltip = function (method) {
Method invocation
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 '
});
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 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 architecture type of this approach is the standard of the jquery plug-in community, which is used by countless plugins, including plugins 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, it's a good practice to give this event a namespace. In this way, when you unbind, you do not interfere with other types of events that may have been bound. You can pass ' .<namespace> ' by appending the namespaces to the events you need to bind.
Copy CodeThe code is 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 the ToolTip is initialized by the Init method, it binds the reposition method to the Resize event and assigns the namespace to the reposition non-method by appending the. 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 without affecting the bindings outside of the plugin.
Ix. data
Usually in the plugin development, you may need to record or check whether your plugin has been initialized to an element. Using the data method of jquery is a good way to record variables based on elements. Nonetheless, it is a better approach to use a separate object to hold all the variables relative to the separated data that records a large number of different names, and to read the object through a separate namespace.
Copy CodeThe code is 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 an object makes it easier to read the properties of all plug-ins from a centralized location.
X. Summary and best practices
Writing a jquery plugin allows you to make libraries and integrate the most useful functionality into reusable code, saving developers time and making development more efficient. When developing jquery plugins, keep in mind that:
1. Always wrap in a closed plug-in:
Copy CodeThe code is as follows: (function ($) {
/* Plugin goes here */
}) (JQuery);
2. Do not redundant package the This keyword within the functionality of the plug-in
3. The This keyword is always returned to maintain chainability unless the plug-in returns a specific value.
4. Pass an extensible default object parameter instead of a large number of parameters to the plugin.
5. Do not name the different methods multiple times in a plugin.
3. Always namespace methods, events, and data.
jquery Plugin Development Detailed tutorial