如何将回调方法发送到另一个回调方法

时间:2015-02-07 06:55:10

标签: javascript jquery

我正在开发一个自定义的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?或者我错过了什么?

1 个答案:

答案 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) );