0

我将以下方法添加到对象中:

loadAPIServiceData : function(service, format, term, callback) {
        return $.when($.ajax({
            url: service + ((term) ? term : '') + '?format=' + format
        })).done(function(result) {
            return callback.apply(result, [ result ]);
        });
    },

回调函数被传递了一个参数,当我加载数据时,我需要在链中进一步向下传递(result显然得到了我从 AJAX 调用返回的任何内容)。我需要的是能够在调用回调函数时向回调函数添加更多参数,并且仍然result在其中:)

更明确地说,这就是我说“我需要能够在回调函数被调用时向回调函数添加更多参数,并且仍然result在那里”时的意思:

var test = loadAPIServiceData('some_service', 'json', 'some_term', function(result, another_parameter, ...) {

});
4

2 回答 2

1

您可以将bind用于应用参数,而无需修改loadAPIServiceData

function myCallback(arg1, arg2, result) {
    //
}

loadAPIServiceData(service, format, term, myCallback.bind(this, arg1, arg2));

如果您更喜欢保持result在第一个 arg 位置,则此代码使用arguments 对象将所有附加参数发送到回调:

loadAPIServiceData : function(service, format, term, callback) {
    var add_args = Array.prototype.slice.call(arguments, 4);

    return $.when($.ajax({
        url: service + ((term) ? term : '') + '?format=' + format
    })).done(function(result) {
        return callback.apply(this, result, [ result].concat(add_args));
    });
},

function myCallback(result, arg1, arg2) {
    //
}

loadAPIServiceData(service, format, term, myCallback, "arg1", "arg2");
于 2012-11-10T14:22:05.643 回答
0

Not sure if I understood your question correctly but does this make sense?

function addOptionalParams(result) {
    var params = [];
    params.push(result);

    // do logic to decide if you need more params
    // if you need more params, push them to the params array
    if(weNeedMoreParams) {
        params.push('foo');
        params.push('bar');
    }

    return params;
}

loadAPIServiceData : function(service, format, term, callback) {
    return $.when($.ajax({
        url: service + ((term) ? term : '') + '?format=' + format
    })).done(function(result) {
        var callbackArgs = addOptionalParams(result);

        return callback.apply(this, callbackArgs);
    });
},

It is the 'done' function which determines which parameters it will invoke the callback with.

于 2012-11-10T13:52:48.300 回答