目的开发基于jQuery的组件,类似官网的jQuery UI。
A、准备知识
A.1、(function(){})();
我们发现很多javascript代码中,都有类似的代码。
如,jquery中是(function(window, undefined ) {…})(window);
如,jqueryUI中是(function( $, undefined ) {…})(jQuery);
该段代码的实质是,先声明一个匿名函数function(arg0){…},声明完成直接调用该函数。其中arg0是个刑参,用在匿名函数内部调用。由于操作符的优先级,函数本身也需要用括号 (function(arg0){}) 。这时我们就已经完成一个匿名函数的定义。在要调用这个匿名函数,就需要给上实参(function(arg0){…})(arg1); 。
举例说明:
如:
(function(str){
})("output");
相当于:
function OutPutFun(str){
};
OutPutFun("output");
A.2、jQuery.extend()和jQuery.fn.extend()
jQuery.extend( target [, object1 ] [, objectN ] )
Merge the contents of two or more objects together into the first object.
把两个或多个对象的内容合并到第一个对象中。
jQuery.fn.extend( object )
Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin).
为扩展的jquery元素设置对外提供的新方法(用于制作标准的jquery插件)。
A.3、javascript中的apply()和call()
首先我们要明白function函数是一个typeof类型为function的对象。而call()和apply()都属于Function.prototype的一个方法。所以每个function对象都有call和apply方法。这两个方法的作用就是执行该函数。区别在于传递参数的方式不同。
function print(a, b, c, d){
};
function example(a, b , c , d){
};
example('a' , 'b' , 'c', 'd');
A.4、Array.prototype.slice.call( arguments, 1 )
首先我们要知道arguments是函数的内置变量,就是参数组成的数组。Array是内置的数组类,而slice是类的内置方法。(和java的static静态方法有点像)。内置的类型可以通过prototype找到内置的属性方法。Array.prototype.slice (start, [end])就是其内置方法。Array.prototype.slice.call( arguments, 1 )的方法返回把参数数组中去除第一个参数后组成的新数组。
B、jQuery plugin
B.1、Getting Started入门
To write a jQuery plugin, start by adding a new function property to the jQuery.fn object where the name of the property is the name of your plugin:
写jQuery插件,从给jQuery.fn对象增加一个新的功能属性开始,jQuery.fn对象属性的名字就是你的插件的名字。
jQuery.fn.myPlugin = function() {
};
But wait! Where's my awesome dollar sign that I know and love? It's still there, however to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
为了防止你的插件和其它使用$的库冲突,最好的办法就是通过直接调用函数表达式把jQuery传递给$。
(function( $ ) {
})( jQuery );
B.2、Context上下文
Now that we have our shell we can start writing our actual plugin code. But before we do that, I'd like to say a word about context. In the immediate scope of the plugin function, the this keyword refers to the jQuery object the plugin was invoked on. This is a common slip up due to the fact that in other instances where jQuery accepts a callback, the this keyword refers to the native DOM element. This often leads to developers unnecessarily wrapping the this keyword (again) in the jQuery function.
this关键词指的是jQuery对象,就是被调用的插件。所以没必要使用$(this)来表示。
(function( $ ) {
})( jQuery );
B.3、return返回值
(function( $ ){
})( jQuery );
这个插件是返回所有jQuery对象中,最高的高度。返回最高高度的值。
var tallest = $('div').maxHeight();
B.4、Maintaining Chainability
The previous example returns an integer value of the tallest div on the page, but often times the intent of a plugin is simply modify the collection of elements in some way, and pass them along to the next method in the chain. This is the beauty of jQuery's design and is one of the reasons jQuery is so popular. So to maintain chainability in a plugin, you must make sure your plugin returns the this keyword.
很多时候,一个插件的目的是修改一组元素。并把修改后的jQuery对象返回,交由调用者处理。
(function( $ ) {
return this;
})( jQuery );
这个插件是修改背景色,并返回jQuery对象。
$('#abc').myPlugin().css("background-color","#0F0");
若没有return this;再修改背景色就不能了。
B.5、Defaults and Options选项
For more complex and customizable plugins that provide many options, it's a best practice to have default settings that can get extended (using $.extend) when the plugin is invoked. So instead of calling a plugin with a large number of arguments, you can call it with one argument which is an object literal of the settings you would like to override. Here's how you do it.
})( jQuery );
B.5、Namespacing命名空间
Properly namespacing your plugin is a very important part of plugin development. Namespacing correctly assures that your plugin will have a very low chance of being overwritten by other plugins or code living on the same page. Namespacing also makes your life easier as a plugin developer because it helps you keep better track of your methods, events and data.
命名空间很重要,好的命名空间和防止你的插件和其他插件的冲突的可能。
B.6、Plugin Methods插件方法
Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object.
This is a discouraged because it clutters up the $.fn namespace. To remedy this, you should collect all of your plugin's methods in an object literal and call them by passing the string name of the method to the plugin.
(function( $ ){
//并把参数method传递给该函数
//找不到对于的方法
else {
})( jQuery );
// 第一个参数空,调用init对于的函数
$('div').tooltip();
// 第一个参数为对象,调用init对于的函数,并把参数传递给该函数
$('div').tooltip({
});
//第一个参数为字符串,并在方法列表中找到,就调用对于的函数
$('div').tooltip('hide');
//第一个参数为字符串,就调用对于的函数,并把后续参数传递给该函数
$('div').tooltip('update', 'This is the new tooltip content!');
B.6、Plugin Events插件事件
A lesser known feature of the bind method is that is allows for namespacing of bound events. If your plugin binds an event, its a good practice to namespace it. This way, if you need to unbind it later, you can do so without interfering with other events that might have been bound to the same type of event. You can namespace your events by appending “.” to the type of event you're binding.
bind方法的一个鲜为人知的功能就是为命名空间绑定事件。若你的插件要绑定一个事件,一种好的解决方法就是命名这个事件。这样一来,若你要解除绑定的这个事件,你就可以直接解除它,而不会干扰可能已经绑定的同类型的其它事件。你可以通过添加.namespace来命名你要绑定的事件。
(function( $ ){
})( jQuery );
B.7、Plugin Data插件数据
Often times in plugin development, you may need to maintain state or check if your plugin has already been initialized on a given element. Using jQuery's data method is a great way to keep track of variables on a per element basis. However, rather than keeping track of a bunch of separate data calls with different names, it's best to use a single object literal to house all of your variables, and access that object by a single data namespace.
在插件开发中,你可能需要维持状态或检查你的插件是否初始化完成。
(function( $ ){
})( jQuery );
B.8、Summary and Best Practices总结和最佳实践
Always wrap your plugin in a closure: (function( $ ){ })( jQuery );
用以下形式包裹你的插件。(function( $ ){})( jQuery );
Don't redundantly wrap the this keyword in the immediate scope of your plugin's function
在插件直接范围内使用this。
Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability.
除非有特殊需求,否则就return this;
Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults.
用对象来代替大量参数。
Don't clutter the jQuery.fn object with more than one namespace per plugin.
不要为一个插件注入一个以上的jQuery.fn命名空间。
Always namespace your methods, events and data.
为方法,事件和数据使用命名空间。