我正在使用Plupload file uploader在一个表格内。我想自定义它,以便当提交表单时,即单击“提交”按钮时,首先发生的是文件上传,然后是提交表单。
据我所知,我可能是错的,但似乎调用 uploader.start()
是一个异步函数调用。现在,上传将开始,表单将在文件上传之前提交。问题是我无法控制这个函数调用。
我最近读到了有关 new release of jQuery 1.5 的内容和新的Deferred Object看起来这有可能帮助我解决这个问题。有没有办法等待异步函数调用完成其工作,然后在调用后继续执行代码。所以我正在寻找类似以下伪代码的内容...
var uploader = $('#plupload_container').pluploadQueue();
$('#submitButton').click(function() {
// if there are files to be uploaded, do it
if (uploader.files.length > 0) {
// make the call and wait for the uploader to finish
uploader.start();
while ( the uploading is not done ) {
wait for the uploader to finish
}
// continue with submission
}
});
有没有办法“等待”uploader.start()
最后,本质上是在单击事件处理程序上暂停,以便可以先上传所有文件,然后单击事件处理程序的其余部分可以完成执行?我已尝试以下操作,但在文件上传完成之前打印了“完成”...
$.when(uploader.start()).then(function () {
console.log("done")
});
另一个有用的信息...我可以将某些事件绑定(bind)到此 uploader
对象实例,例如“UploadProgress”或“UploadComplete”。例如,我可以使用延迟对象以某种方式捕获“UploadComplete”事件触发时的情况吗?有 AJAX-y 方法可以做到这一点吗?
谢谢。
最佳答案
您的问题是,尽管 uploader.start
做了一些异步操作以使代码正常工作,但 uploader.start
必须返回 jquery $.deferred
对象。
来自 uploader 插件的最新来源:
/**
* Starts uploading the queued files.
*
* @method start
*/
start : function() {
if (this.state != plupload.STARTED) {
this.state = plupload.STARTED;
this.trigger("StateChanged");
uploadNext.call(this);
}
},
因此它不会返回延迟对象。相反,在 uploadNext
函数中,有这样一行代码:
this.trigger("上传完成", 文件);
所以我们只需绑定(bind)到您的上传者,
uploader.bind("UploadComplete", function(files) {
// your code
});
我从未使用过该插件,但这个 should工作。祝你好运。
如果你必须使用延迟,那么你总是可以像这样的伪代码:
var uploader = $('#plupload_container').pluploadQueue();
var def = $.Deferred();
uploader.bind("UploadComplete", function(files) {
def.resolve(files);
});
$('#submitButton').click(function() {
if (uploader.files.length > 0) {
uploader.start();
def.done(function(files) {
def = $.Deferred(); // reset the deferred object.
// rest of your click handler.
});
}
});
关于jquery - 我将如何使用 jQuery.Deferred 对象来等待异步函数调用完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934794/