【发布时间】:2012-10-26 17:41:28
【问题描述】:
我有一种情况,我需要保存一个 Backbone 模型,然后在它成功时遍历一个集合并保存它们,然后在每个成功时遍历另一个集合并保存它们,然后在所有这些都完成后执行一个AJAX 请求。这就是我所拥有的:
backboneModel.save(
{},
{
wait: true,
success: function (model1, response1)
{
$.each(backboneCollection1.models, function () {
this.save(
{},
{
wait: true,
success: function (model2, response2)
{
$.each(backboneCollection2.models, function () {
this.save(
{},
{
wait: true,
success: function (model2, response2)
{
//If i put the AJAX request here it will happen for every iteration which is not desired
}
});
});
}
});
});
//If i put the AJAX request here it will fire after one iteration of the first each even with async set to false on the AJAX request
}
});
是否有人对在何处执行此 AJAX 请求有任何建议,以便在所有主干模型保存到服务器后仅触发一次?
【问题讨论】:
-
我认为最大的问题是结构设置错误。一方面,您的最后一次收藏保存实际上将进行 N 次保存,数量级为主干Collection1.length。因此,如果 collection1.length 为 10 且 collection2.length 为 5,您将进行 10 次调用以将模型保存在 collection1 中,但进行 50 次调用以仅将 5 个模型保存在 collection2 中。我正在尝试为您提供一个使用 jQuery 承诺并执行您正在尝试的解决方案,但我正在工作,所以可能需要一段时间。
标签: jquery ajax backbone.js