【问题标题】:How to pass parameters with jquery proxy() to a function which has already other parameters如何使用 jquery proxy() 将参数传递给已经有其他参数的函数
【发布时间】:2014-08-03 16:06:54
【问题描述】:

按照要求,我已将代码更新为我的具体问题:

function A(){
    this.data1 = null;
    this.data2 = null;
}
A.prototype.receiveData1AndData2FromServer = function(callback){
    this.doneCallback = $.proxy( function foo(importantData, callback){
        this.data1 = importantData.data1;
        this.data2 = importantData.data2;
        callback != undefined ? callback() : null;
    }, this, callback);

    checkFail = $.proxy(
        function (jqXHR, textStatus, errorThrown) {
            try {
                var str = new String(jqXHR.responseText);
                var result = JSON.parse(str.substring(str.indexOf('{')));
                this.doneCallback(result);
            } catch (ex) { console.log(ex); }
        }
    , this);
    $.ajax({
        type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
    }).done(this.doneCallback)
    .fail(checkFail);
    }

(问题是回调参数正在替换第一个参数(importantData)而不是第二个。)

对 A::receiveData1AndData2FromServer 有不同回调参数的调用。 我想将回调传递给A::doneCallback,所以当检索完成时,会调用正确的回调。

【问题讨论】:

  • 这看起来很奇怪,试着解释一下你想要做什么,因为肯定有其他方法比这个`

标签: javascript jquery parameter-passing


【解决方案1】:

你的问题不是很清楚,但是jQuery.proxy() 从 1.6 版本开始支持多个参数

【讨论】:

    【解决方案2】:

    经过一番思考,我找到了解决方案。 将上下文参数拆分为具有多个字段(上下文和所需参数)的对象已经解决了它。我希望它对其他人有用。

    function A(){
        this.data1 = null;
        this.data2 = null;
    }
    A.prototype.receiveData1AndData2FromServer = function(callback){
        this.doneCallback = $.proxy( function foo(importantData, callback){
            this.context.data1 = importantData.data1;
            this.context.data2 = importantData.data2;
            this.callback.callback != undefined ? this.callback() : null;
        }, {context:this, callback:callback});
    
        checkFail = $.proxy(
            function (jqXHR, textStatus, errorThrown) {
                try {
                    var str = new String(jqXHR.responseText);
                    var result = JSON.parse(str.substring(str.indexOf('{')));
                    this.doneCallback(result);
                } catch (ex) { console.log(ex); }
            }
        , this);
        $.ajax({
            type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
        }).done(this.doneCallback)
        .fail(checkFail);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 2015-06-02
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多