我正在开发一个自定义的jQuery插件,我已经给出了以下选项来相应地修改插件:
onSuccess: false, // callback
afterSuccess: false, // callback
beforeRequest: 'searching ...',
这就是我在插件中处理这些回调的方法,
/* --------------- Click Event on Dynamic Elements ------------------ */
this._afterSuccess( this.parent, this.$el, this.extraElement, this._removeContainer );
正如您在上面的代码中看到的那样this._removeContainer
是一种我想发送afterSuccess
回调的方法。
_afterSuccess: function( parent, element, extraElement, removeContainer ) {
var that = this;
if( typeof this.options.afterSuccess == "function" ) {
// Trigger callback if found
this.options.afterSuccess.call( this, parent, element, extraElement, removeContainer );
}
else {
parent.on('click', 'li a', function(e) {
e.preventDefault();
var id = $(this).data('key');
var text = $(this).text();
that.$el.val(text);
that._removeContainer();
that.extraElement.val(id);
});
}
},
_removeContainer: function() {
this.response_container.html('');
this.extraElement.val('');
},
这就是我实现插件的方式:
$('#some_element').MyPlugin( {
afterSuccess: function(parent, element, extraElement, removeContainer) {
parent.on('click', 'li a', function(e) {
e.preventDefault();
var id = $(this).data('key');
var text = $(this).text();
element.val(text);
// Not working Generating Error
removeContainer();
extraElement.val(id);
});
}
} );
removeContainer()
生成错误'response_container'未定义有没有更好的方法来调用this._removeContainer()
回调方法中的afterSucess
?或者我错过了什么?
答案 0 :(得分:2)
尝试将上下文设置为removeContainer
,因为现在this
中的removeContainer
引用了全局window
,但window
中没有response_container
,像这样
this.options.afterSuccess.call( this, parent, element, extraElement, $.proxy( removeContainer, this ) );
<强>更新强>
this.options.afterSuccess.call( this, parent, element, extraElement, removeContainer.bind(this) );