About the development of jquery Plug-ins have done a little research, they have written a number of plug-ins, in their own team has also shared a lesson on plug-ins. At the beginning, the whole complex of the code, now look at the time is much clearer. Here I share what I have summed up to help those who have met the same problems as I have.
What am I going to do?
I want to get the JavaScript plugin should have the following several characteristic code the independent chained operation plug-in can be configured with an operable method, the plug-in lifecycle controllable configuration can be cached extensible conflict-free handling event agent, dynamic initialization
The following code assumes the existence of the first form of the JQuery plugin
In the face of this, we usually do this by defining the function.
The code is as follows:
function Pluginname ($selector) {
$.each ($selector, function () {
$ (this). CSS ("Background-color", "#ccc");
To do something
;}
Pluginname (Document.getelementsbyclassname ("demo"));
Because I'm talking about jquery plugin development, I'm now extending this code to jquery, and the code is as follows:
The code is as follows:
;(function ($) {
//extend this method to jquery.
$.extend () is the bar method extends to the $ object, unlike $.fn.extend. When extended to $.fn.xxx, the
//call can be $ (selector). XXX ()
$.fn.extend ({/
/plugin name
pluginname:function () {/
/ Traversal of a collection of matching elements
//Note here is a "return", the role is the processing of the object returned to implement the chain of Action returns
This.each (function () {
//write the appropriate code here to handle
} );
}
});
Pass jquery to the inner scope, and if window,document is used more, it can also be passed in here.
}) (JQuery, window, document, undefined);
}) (JQuery, undefined);
Call Mode $ (". Selector"). Pluginname (). Othermethod ();
But it's still a long way off, and it only solves two problems.
Code is relatively independent
the second form of chained operation Plug-ins
Now to add parameter support to the plug-in
The code is as follows:
;(function ($) {
$.fn.pluginname = function (options) {
//merge parameters, combining default and custom parameters with "Extend"
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
Code is relatively independent
Chained operation
Plug-in configurable third form of plug-in
Now to add support for the method, the lifecycle I mentioned earlier is controllable, meaning similar, such as adding reinit,destory to control plug-ins.
The code is as follows:
;(function ($) {$.fn.pluginname = function (method) {//If the first argument is a string, find out if it exists, call it, and call the Init method if it is an object
;. if (Methods[method]) {//If the method is present this method is called/apply Yes Obj.method (arg1, arg2, ARG3) Convert to methods (obj, [
Arg1, Arg2, Arg3]) process.
Array.prototype.slice.call (arguments, 1) converts the parameters of a method to an array.
Return methods[method].apply (this, Array.prototype.slice.call (arguments, 1));
else if (typeof method = = = ' object ' | |!method) {//If the incoming argument 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 to the $.fn.pluginname. Build a "methods" in the closure to preserve the method, similar to a common method. var methods = {/** * Initialization method * @param _options * @return {*}/init: function (_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); Call Mode//$ ("div"). Pluginname ({...}); Initialize//$ ("div"). Pluginname ("Publicmethod"); Call method
and solve a problem
Code is relatively independent
Chained operation
Plug-ins can be configured
There is an operable method, the plug-in lifecycle can be controlled in the fourth form of Plug-ins
The third form of plug-in modification can already deal with the needs of most plug-ins. Keep improving, and continue to upgrade.
The four-form plug-in is the code for Masaki's JavaScript frame design. Added a bit of object-oriented knowledge.
The code is as follows:
(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
Rationale 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") {
Methods of executing Plug-ins ui[options].apply (UI, args);
}
});
};$.fn.pluginname.defaults = {};
}) (JQuery); Called the same way as before.
Here special to mention caching this thing, plug-ins use more, feel this is really a good thing.
In the traditional object-oriented plug-in development, at least declare a variable to save it, but I do not have to write the jquery plug-ins are not, it is cumbersome to use. Since the initialization of the plug-in cache after a lot of convenience. You can get the object by using code $ ("#target"). Data ("Pluginname"). Let's see what else is wrong.
Code is relatively independent
Chained operation
Plug-ins can be configured
There are operable ways to control the life cycle of Plug-ins
Configure the fifth form of a cached plug-in
See the above code whether the brain is a little dizzy, if it is, take a break, come back later, the following code more exciting. The last option is more comprehensive. The scenario comes from Bootstrap, and the following code takes the Bootstrap button plug-in as an example.
The code is as follows:
!function ($) {//ECMA262V5 's new stuff, enforces 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 likely to be a previously defined plugin, where no conflict handling is used.
$.fn.button = function (option) {return This.each (function () {var $this = $ (this);
Determines whether the initialization is based on var data = $this. Data (' Bs.button ');
var options = typeof option = = ' object ' && option; If it is not initialized, it initializes the IF (!data) $this. Data (' Bs.button '), (data = New Button (This, options)));
if (option = = ' Toggle ') data.toggle ();
else if (option) data.setstate (option)})};
① Exposure class name, you can do this for the plug-in custom extension $.fn.button.constructor = button;
Extension//set: $.fn.button.constructor.newmethod = function () {}//use: $btn. Button ("Newmethod");
② no conflict handling $.fn.button.noconflict = function () {$.fn.button = old;
return this}; ③ Event Agent, Smart initialization $ (document). On (' Click.bs.button.data-api ', ' [Data-toggle^=button] ', function (e) {var $btn =
$ (e.target);
Finds the object to initialize if (! $btn. Hasclass (' btn ')) $btn = $btn. Closest ('. btn ');
Call the method directly, and if not initialized, the internal initialization $btn. button (' Toggle ');
E.preventdefault ();
}); } (JQuery);
Let's see what else is wrong.
Code is relatively independent
Chained operation
Plug-ins can be configured
There are operable ways to control the life cycle of Plug-ins
Configuration can be cached
Can be extended
No conflict handling
Event agent, dynamic initialization supplement
Today's plug-ins require a high flexibility, such as the hope that plug-ins can be suitable for both jquery and zepto, or need to support AMD or CMD specifications.
Support for jquery and Zepto
The code is as follows:
if (window.jquery | | window. Zepto) {
(function ($) {
//Plugin code ...
}) (window.jquery | | window.) Zepto);
}
Middleware Support, node
The code is as follows:
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 there is not understand where to see more. After a few see do not understand also has no relationship, in the actual development, the front a few enough. To emphasize, not the more advanced writing the better, to see their own project needs reasonable choice.
Well, today's summary on the first here, if we have a better way of plug-in development, please let me know. I hope you can enjoy this article.