A summary of five forms of jquery plug-in development _jquery

Source: Internet
Author: User
Tags class definition

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?
The JavaScript plugin I want to get should have the following features

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

* The following code assumes the existence of JQuery

The first form of the plugin

In the face of this, we usually do this by defining the function.

Copy Code code 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:

Copy Code code as follows:

Iife (call function expression immediately); [Reference http://suqing.iteye.com/blog/1981591/]
;(function ($) {
Extend this method to jquery.
$.extend () is the bar method extends to the $ object, unlike $.fn.extend. After extending to the $.fn.xxx,
It can be $ (selector) when invoked. XXX ()
$.fn.extend ({
Plugin Name
Pluginname:function () {
Traversing a collection of matching elements
Note that there is a "return", which is the function of returning the processed object and realizing the chain operation.
Return 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
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

Second form of plug-in

Now to add parameter support to the plug-in. The code is as follows

Copy Code code as follows:

;(function ($) {
$.fn.pluginname = function (options) {
Merging parameters, merging 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 parameters
$.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-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

The third form of the plugin

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.

Copy Code code as follows:

;(function ($) {
$.fn.pluginname = function (method) {
If the first argument is a string, find out if the method exists and call it; If it is an object, the Init method is invoked;.
if (Methods[method]) {
This method is invoked if the method is present
Apply is the process of converting Obj.method (arg1, arg2, Arg3) into method (obj, [Arg1, Arg2, Arg3]).
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 passed in 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 parameters
$.fn.pluginname.defaults = {
};
}) (JQuery);
Call mode
$ ("div"). Pluginname ({...}); Class
$ ("div"). Pluginname ("Publicmethod"); Call method

and solve a problem

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

The fourth form of the plugin

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.

Copy Code code 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) {
Merging parameters
Return This.each (function () {
Write the appropriate code here to handle
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);
Caching Plug-ins
$._data (This, "Pluginname", UI);
}
Call method
if (typeof options = = "string" && typeof ui[options] = = "function") {
Ways to execute 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
Configuration can be cached
Can be extended
No conflict handling
Event Agent, dynamic initialization

The fifth form of the plugin

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.

Copy Code code as follows:

!function ($) {
ECMA262V5 new things, 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 likely to be a previously defined plugin, where no conflict handling is used.
$.fn.button = function (option) {
Return This.each (function () {
var $this = $ (this);
The basis for judging whether or not to initialize
var data = $this. Data (' Bs.button ');
var options = typeof option = = ' object ' && option;
If it's 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
})
};
① exposes the class name, you can do this for the plug-in customization extension
$.fn.button.constructor = button;
Ways to expand
Setting: $.fn.button.constructor.newmethod = function () {}
Use: $btn. Button ("Newmethod");
② No conflict handling
$.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 ');
Call the method directly, and if not initialized, the interior is initialized first
$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

Add

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

Copy Code code as follows:

if (window.jquery | | window. Zepto) {
(function ($) {
Plugin code ...
}) (Window.jquery | | | window. Zepto);
}

Middleware Support, node

Copy Code code 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.

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.