【发布时间】:2017-01-02 16:04:24
【问题描述】:
基本上我想做的和这个类似;
function methodX(arg1, arg2, ...) {}
methodX([arg1, arg2, arg3]);
在实际场景中,我有一个数组 (cbInfo),我正在尝试将它与 jQuery.when() 一起使用,如下所示,它似乎不起作用。那么有没有办法为需要 N 个参数的函数传递参数数组?
var cbInfo = [
{
templatePath: 'templates/level.html',
callback: renderLevels
},
{
templatePath: 'templates/alert.html',
callback: renderAlerts
}
];
function loadTemplates(cbInfo, cb) {
var ajaxes = [],
callbacks = [];
cbInfo.forEach(function (elem) {
ajaxes.push($.ajax({type: "GET", url: elem.templatePath}));
callbacks.push(elem.callback)
});
$.when(ajaxes).then(
function () {
var args = Array.prototype.slice.call(arguments);
callbacks.forEach(function (elem, index) {
elem(args[index]);
});
cb();
},
function () {
// failure
console.error("loadTemplates() : could not load UI templates.")
}
);
}
更新:
apply 和 spread 运算符都在其他情况下工作。但我正在尝试针对这种特定情况解决这个问题。我尝试使用 $.when().apply(null, ajaxes),但随后抛出 Uncaught TypeError: $.when(...).apply is not a function 如何克服这个问题?而且,我也需要支持 ES5。
【问题讨论】:
标签: javascript jquery ajax .when