问题描述
我正在尝试在数组中与$.when()
一起使用一组延迟函数.这些函数从服务器获取数据并将其呈现在DOM中.完成所有这些操作后,将加载一些脚本并执行几个后加载操作.
I am trying to use a variable set of deferred functions in an array along with $.when()
. These functions fetch data from the server and render it in the DOM. After all these are done, some scripts are loaded and a couple post-load actions are performed.
这是我正在使用的:
function loadAllGames(updateGames, updatePlayoffs) {
var deferredLoads = [];
if (updateGames !== false)
deferredLoads.push($.Deferred(loadGames));
if (updatePlayoffs !== false)
deferredLoads.push($.Deferred(loadPlayoffs));
$.when.apply($, deferredLoads).done(loadPostGamesLoadData);
}
问题在于loadPostGamesLoadData
从未被调用.
loadGames
和loadPlayoffs
都返回承诺:
function loadGames() {
$.get('{% url wave_spinner_template %}', {message: 'Loading games...'}, function (data) {
$('#weeks').html(data);
});
return $.ajax({
url: "{% url weeks season.id %}",
success: function (data) {
$('#weeks').html(data);
},
error: function () {
console.log("Error loading games.");
}
});
}
function loadPlayoffs() {
$.get('{% url wave_spinner_template %}', {message: 'Loading playoffs...'}, function (data) {
$('#playoffs').html(data).children('.spinner-container').addClass('border-top');
});
return $.ajax({
url: "{% url playoffs season.id %}",
success: function (data) {
var $playoffs = $('#playoffs');
if (!$playoffs.length) {
$playoffs = $('<div>', {id: 'playoffs'});
$('#weeks').after($playoffs);
}
$playoffs.html(data);
},
error: function () {
console.log("Error loading playoffs.");
}
});
}
推荐答案
您错误地创建了延迟对象;实际上,您根本不应该创建它们. $.Deferred
接受的函数是工厂函数,恰好在$.Deferred
返回之前运行,该函数接收新的延迟对象作为参数(因此您可以将处理程序附加到该对象). ( API文档中的详细信息.)这完全不是loadGames
所能做到的, ;他们返回一个延迟的对象.因此,您最终遇到了无法解决的延迟对象.
You're creating the deferred objects incorrectly; indeed, you shouldn't be creating them at all. The function accepted by $.Deferred
is a factory function run just before $.Deferred
returns which receives the new deferred object as an argument (so you can attach handlers to it). (Details in the API docs.) That's not what loadGames
and such do at all; they return a deferred object. So you end up with deferred objects that nothing ever settles.
由于它们已经已经从$.ajax
中延迟了对象,而您要返回这些对象,因此直接使用这些函数即可:
Since they already have deferred objects from $.ajax
, which you're returning, just use those functions directly:
function loadAllGames(updateGames, updatePlayoffs) {
var deferredLoads = [];
if (updateGames !== false)
deferredLoads.push(loadGames());
// ------------------------^^^^^^^^^^^
if (updatePlayoffs !== false)
deferredLoads.push(loadPlayoffs());
// ------------------------^^^^^^^^^^^^^^
$.when.apply($, deferredLoads).done(loadPostGamesLoadData);
}
这篇关于$ .when()与Deferreds数组不调用完成的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!