About the development of jquery plug-in has done a little research, I have also written a number of plugins, in their own team has also shared a lesson on the plugin. The beginning of the whole sleep of the very complex code, now look at the time is clear a lot. Here I share what I have summed up and help those who have met the same problems as I have.
What am I going to do?
What I want to get is javascript 插件
supposed to have some of the following characteristics
* 以下的代码均假设存在 jQuery
The first form of the plugin
In the face of this situation, we usually function
implement it in a defined way.
function Pluginname ($selector) { $.each ($selector, function () { $ (this). CSS ("Background-color", "#ccc"); To do something ... });} Pluginname (Document.getelementsbyclassname ("demo"));
Because I'm talking about jquery plug-in development, I'm now extending this code to jquery with the following code:
Iife (call function expression immediately); [Reference http://suqing.iteye.com/blog/1981591/];(function ($) { //extend this method to jquery. $.extend () is the method that extends to the $ object, unlike the $.fn.extend. When extended to $.fn.xxx, the //call can be $ (selector). XXX () $.fn.extend ({ //plugin name pluginname:function () {/ / Iterate over the collection of matching elements //Note there is a "return", which is the function of returning the processed object, implementing the chain Operation return This.each (function () { //writing the appropriate code for processing here }); } });/ /pass JQuery to the inner scope, if window,document is used more, it can also be passed here./}) (jquery, window, document, undefined);}) (JQuery, undefined);//Call Way $ (". Selector"). Pluginname (). Othermethod ();
But it's still a long way off, and there are only two problems solved.
The second form of the plugin
Now to add parameter support to the plugin. The code is as follows
;(function ($) { $.fn.pluginname = function (options) { //merge parameters, combine default parameters with "Extend" and custom parameters var args = $.extend ({ }, $.fn.pluginname.defaults, options); Return This.each (function () { console.log (args.text); To do something ); }; Default parameter $.fn.pluginname.defaults = { text: "Hello" };}) (jQuery);//$ (". Selector"). Pluginname ({// text: "Hello world!" // });
Adding parameter support is easier and solves a problem
The third form of the plugin
Now to add support for the method, the life cycle I mentioned earlier can be controlled , meaning similar, such as adding reInit
, destory
and other methods to control the plugin.
;(function ($) {$.fn.pluginname = function (method) {//If the first argument is a string, find out if the method exists, call it if it is found, or call the Init method if it is an object). if (Methods[method]) {//If the method is present, call the method//Apply Yes Obj.method (arg1, arg2, Arg3) Convert to Method ( The process of obj, [Arg1, Arg2, Arg3]). Array.prototype.slice.call (arguments, 1) is the conversion of the method's parameters to an array. Return methods[method].apply (this, Array.prototype.slice.call (arguments, 1)); } else if (typeof method = = = ' object ' | |!method) {//If the passed in parameter is ' {...} ', it is considered an initialization operation. Return methods.init.apply (this, arguments); } else {$.error (' method ' + method + ' does not exist on Jquery.pluginname '); } }; Do not extend the method on the $.fn.pluginname. Create a "methods" in the closure to save the method, similar to the common method. var methods = {/** * Initialization method * @param _options * @return {*} */Init:functi On (_options) {return This.each (function () {var $this = $ (this); VaR args = $.extend ({}, $.fn.pluginname.defaults, _options); // ... }) }, Publicmethod:function () {Private_methods.demomethod (); } }; Private Method Function Private_methods = {demomethod:function () {}}//default parameter $.fn.pluginname.defaults = { };}) (jQuery);////$ ("div"). Pluginname ({...}); Initialize//$ ("div"). Pluginname ("Publicmethod"); Calling methods
and solve a problem.
The fourth form of the plugin
The third form of plug-in modification can already handle the needs of most plug-ins. Keep improving, continue to upgrade.
The four-form plug-in is the code of Help. 司徒正美
《javascript框架设计》
Added a bit of object-oriented knowledge.
(function ($) {var Plugin = function (element, options) {this.element = element; this.options = options; }; Plugin.prototype = {create:function () {console.log (this.element); Console.log (this.options); } }; $.fn.pluginname = function (options) {//merge parameter return This.each (function () {///write the appropriate code here for processing var UI = $._data (This, "pluginname"); If the element is not initialized (possibly a newly added element), it is initialized. if (!ui) {var opts = $.extend (true, {}, $.fn.pluginname.defaults, typeof options = = = "Object"? Options: {}); UI = New Plugin (this, opts); Cache plugin $._data (this, "Pluginname", UI); }//Call method if (typeof options = = = "string" && typeof ui[options] = = "function") { The method of executing the plug-in ui[options].apply (UI, args); } }); }; $.fn.pluginname.defaults = {};}) (jQuery);//called in the same way as before.
Here specifically to mention the cache this thing, plug-in with more, feel this is really good things.
In the traditional object-oriented plug-in development, at least declare a variable to save it, but I do not write the jquery plugin, it is cumbersome to use. Since the initialization of the plugin cache after the convenience of a lot. The $("#target").data("pluginName")
object can be taken from the code. Let's see if there's any problem.
The fifth form of the plugin
See the above code whether the brain a little dizzy, if it is, rest a moment, come back later, the following code is more exciting. The last scheme is more comprehensive. Scenario Bootstrap
, the following code takes the Bootstrap button plug-in as an example.
!function ($) {//ECMA262V5 new stuff, forcing the use of rigorous code writing. "Use strict"; Button public CLASS DEFINITION//============================== var Button = function (element, options) { this. $element = $ (element); This.options = $.extend ({}, Button.defaults, options); }; Button.defaults = {loadingtext: ' Loading ... '}; Button.prototype.setState = function (state) {//...}; Button.prototype.toggle = function () {//...}; BUTTON PLUGIN DEFINITION//======================== var old = $.fn.button; The $.fn.button here is probably a plugin that has been previously defined, and is used here for conflict-free processing. $.fn.button = function (option) {return This.each (function () {var $this = $ (this); Determine if initialization is based on var data = $this. Data (' Bs.button '); var options = typeof option = = ' object ' && option; If it is not initialized, initialize it if (!data) $this. Data (' Bs.button ', (data = New button (this, options)); if (option = = ' Toggle ') data.toggle (); else if (option) data.setstate (option)}); ① exposes the name of the class, you can do this for the plug-in custom extension $.fn.button.constructor = button; How to extend//set: $.fn.button.constructor.newmethod = function () {}//use: $btn. Button ("Newmethod"); ② Conflict-free processing $.fn.button.noconflict = function () {$.fn.button = old; return this}; ③ Event Agent, intelligent initialization $ (document). On (' Click.bs.button.data-api ', ' [Data-toggle^=button] ', function (e) {var $btn = $ (E.target); Find the object to initialize if (! $btn. Hasclass (' btn ')) $btn = $btn. Closest ('. btn '); The method is called directly, and if it is not initialized, the internal $btn is initialized first. button (' Toggle '); E.preventdefault (); });} (JQuery);
Let's see if there's any problem.
Add
Plug-ins now require a high level of flexibility, such as the need for plug-ins to be available at the same time jQuery
Zepto
, or to support the AMD or CMD specification.
- Support for jquery and Zepto
if (window.jquery | | | window. Zepto) { (function ($) { //Plugin code ... }) (window.jquery | | window. Zepto);}
- Middleware Support, node
if (typeof (module)!== ' undefined ') { module.exports = pluginname;}
- Requirejs (AMD) support
if (typeof define = = = ' function ' && define.amd) { define ([], function () { ' use strict '; return pluginname; });
- SEAJS (CMD) support
if (typeof define = = = ' function ') { define ([], function () { ' use strict '; return pluginname; });
Call ~, the problem is solved, the code if you can not understand the place to see more. The latter few can not understand also has no relationship, in the actual development, the front several enough. To emphasize, not the more advanced the better the wording, to see the needs of their own projects reasonable choice.
Of course, there are more and better plug-in development, waiting for everyone to find out.
jquery plugin development, jquery plugin