我试图更好地理解如何创建 jQuery 插件,并且我的理解基于http://docs.jquery.com/Plugins/Authoring。我在最后,对命名空间和数据感到困惑。
首先(参见下面代码中的问题 1):本教程显示目标 ( $this
) 和工具提示都存储在对象字面量中。
- 存储这些特定变量有什么好处?
- 如果有默认值和自定义选项,这是保存结果设置对象的好地方吗?
另外,他们这样做是有原因$(this).data('tooltip',{target:$this,tooltip:tooltip});
的,而不是$this.data('tooltip',{target:$this,tooltip:tooltip});
?
第二(参见下面代码中的问题 2):本教程展示了如何销毁插件。我明白$this.removeData('tooltip');
了,但是这样做有什么意义data.tooltip.remove();
呢?
来源:http ://docs.jquery.com/Plugins/Authoring#Data
(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
*/
//QUESTION 1
$(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');
QUESTION 2
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 );