我正在开发自定义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?还是我错过了什么?

最佳答案

尝试将上下文设置为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) );

10-04 16:45