[英]learning and expanding a jquery plugin
我正在学习有关javascript插件的更多信息,并发现了一个我感兴趣的插件。 我愿意弄脏自己的脚,看看该如何修改...
(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.如何初始化此插件? 当我尝试运行随机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。 为什么写methods [method] //看起来像[method]是一个数组,这让我感到困惑,因为我看不到数组,它有很多方法...
3b。 其他还要检查什么? 还是为什么会发生错误?
感谢您提供帮助我全面了解此插件的建议!
我不知道你对第一个问题有什么看法。 但是其他问题很容易解决。
首先,让我们越过3。
您拥有的代码以及jQuery在其文档中提供的内容只是您和您的方法之间的一种“获取器”。 无需将命名空间与所有方法组合在一起,而是将方法放入对象标题methods
(在第一个代码块的第二行上实例化)。
如果查看您所询问的jQuery提供的代码,那么它不是您想的那样返回的方法。 它在您的methods
对象中调用 键的methods
。 第一个if语句表示,如果您使用字符串变量调用插件(在您的情况下为工具提示),它将在method对象中查找该索引并调用函数。
第二个else if块表示如果将一个对象作为参数或没有参数传递,它将调用您的init方法。 这有点像为您的插件定制的getter / initializer。
因此,现在,要回答您的第二个问题,可以通过用。调用工具提示插件来访问init方法。
1)没有参数
2)对象参数(通常为{"someOption":true,"anotherOption":400}
)
3) $('#id').tooltip('init')
的字符串'init'
这样,您还可以使用...访问显示和隐藏方法。
$('#id).tooltip('hide')
...依此类推。
您可以在jQuery文档中阅读更多信息。 这只是我将其放在外行的术语中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.