我正在学习更多关于JavaScript插件的过程,并找到了一个对我感兴趣的东西。我愿意让我的脚脏,看看这个东西怎么可以修改...学习和扩展一个jQuery插件
(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) {
console.log('still working..' );
/*
Do more setup stuff here
*/
$(this).data('tooltip', {
target : $this,
tooltip : tooltip
});
}
});
},
show : function() {
console.log('this is the show');
},
hide : function() {
// GOOD
},
update : function(content) {
console.log('this is the update');
// !!!
}
};
$.fn.tooltip = function(method) {
// Method calling logic
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);
好,我有4个问题... 1.how你初始化这个插件?当我尝试运行一个随机的div元素$('#mtest')。tooltip();我一直使用我的控制台日志'仍然工作..'。
2 init:在var方法里面,这是私有的,这意味着我无法从这个插件的外部访问init:?对?我会在哪里放置初始化逻辑,因为它似乎正在返回选项......?
3. 我感到困惑的这部分代码...
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');
}
我知道它返回的所有方法,但...
3A。为什么写方法[方法] //看起来像[方法]是一个数组,并且这看起来让我感到困惑,因为我没有看到一个数组,它的一堆方法...
3b。其他人在检查什么?或者为什么会出现错误?
感谢您的任何意见,帮助我完全理解这个插件!
你看过[jQuery UI Widgets](http://wiki.jqueryui.com/w/page/12138135/Widget%20factory)吗?我最近一直在研究这个,并开始创建一些。 – JoeFletch
看起来很酷,但我不想要一个插件 - 我做了太多的http请求,因为它已经是,并且真的想在单个js页面上做些什么,而与第三方扩展无关......无论如何感谢虽然。 – blackhawk