【发布时间】:2013-11-28 20:53:26
【问题描述】:
上下文
情况如下:用户可以在应用程序中上传文件。他们可以在任何时间(以及多次)这样做。
我想在上传完成时显示一个微调器,并在目前没有上传时将其删除。
我的方法
上传是由外部文件上传插件(如 blueimp)处理的,在它的 add 方法上,我抓取 jqXHR 对象并将它们添加到主干集合(它们是我的应用程序中的图像,所以我将它与 Marionette 结合使用集合视图)。
以下是 Marionette Itemview 的 onRender 回调中调用的函数的一部分:
// Get the file collection
var uploadFiles = SomeBackBoneCollection;
// Track how many deferreds are expected to finish
var expected = 0;
// When an image is added, get the jqXHR object
uploadFiles.bind('add', function(model) {
// Get jqXHR object and call function which tracks it
trackUploads(model.get('jqXHR'));
// Do something to show the spinner
console.log('start the spinner!');
// Track amount of active deferreds
expected++;
}, this);
// Track the uploads
function trackUploads(jqXHR) {
$.when(jqXHR).done(function(){
// A deferred has resolved, subtract it
expected--;
// If we have no more active requests, remove the spinner
if (expected === 0) {
console.log('disable the spinner!');
}
});
}
讨论
这种方法效果很好,尽管我想知道是否还有其他(更好的)方法。
你觉得这个方法怎么样?关于这种方法,您是否看到任何优点或缺点?还有其他方法或建议吗?
例如,拥有某种数组/对象可能会很棒,您可以继续向其传递延迟,并且 $.when 以某种方式监控此集合并在任何时候解决所有问题。但是,这应该可以让您在任何给定时间继续传递延迟对象。
【问题讨论】:
标签: backbone.js marionette jquery-deferred