【发布时间】:2013-05-16 17:05:16
【问题描述】:
我的插件允许您在其选项中指定回调。该插件可能在 DOM 准备好之前运行,但我需要确保回调仅在 DOM 准备好后运行,因此我将 callback.call() 包装在 $( document ).ready() 处理程序中。
问题是我想在回调中维护插件的上下文。换句话说,在回调中,我希望 this 成为插件,而不是 document。
这是我想出的,但我不确定它是否真的是最好的方法。
function MyPlugin( element, options ){
this.element = element;
this.options = $.extend( {}, defaults, options );
MyPlugin.prototype = {
functionWithCallback: function(){
if ( typeof this.options.callback == 'function' )
$( document ).ready( function( plugin ){ plugin.options.callback.call( plugin ) }( this )
}
}
}
最后一行很难看,但它允许我将插件的 this 上下文传递给回调。
我宁愿做 $( document ).ready( this.options.callback ) 并完成它,但是在回调中,this 是 document 这并没有真正的帮助,也不一定让我轻松访问插件的元素被召唤...
有没有更好的办法?
【问题讨论】:
标签: this document-ready jquery-callback jquery-context