我想更好地瞭解如何創建jQuery插件,並基於我的理解http://docs.jquery.com/Plugins/Authoring。我處於最後,對命名空間和數據感到困惑。jQuery插件,數據()和命名空間
首先(見下面的代碼問題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);
謝謝甜菜根 - Beetrot,你理解我的每個問題完善,並給出了很好的答案。 – user1032531