Reputation: 9701
I have the following method added to an object :
loadAPIServiceData : function(service, format, term, callback) {
return $.when($.ajax({
url: service + ((term) ? term : '') + '?format=' + format
})).done(function(result) {
return callback.apply(result, [ result ]);
});
},
The callback function is passed one parameter that I need further down in the chain when I'm loading the data ( the result
obviously gets whatever I get back from the AJAX call ). What I need is to be able to add more parameters to the callback function when it's called, and still have the result
in there :)
To be more explicit about it this is what I was meaning when I said "I need is to be able to add more parameters to the callback function when it's called, and still have the result
in there" :
var test = loadAPIServiceData('some_service', 'json', 'some_term', function(result, another_parameter, ...) {
});
Upvotes: 0
Views: 132
Reputation: 1005
You can use bind for apply arguments without need to modify the loadAPIServiceData
:
function myCallback(arg1, arg2, result) {
//
}
loadAPIServiceData(service, format, term, myCallback.bind(this, arg1, arg2));
If you prefer keep result
in first arg position, this code send all additional argument to the callback, using the arguments object:
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");
Upvotes: 1
Reputation: 21830
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.
Upvotes: 0