使用来自服务器的文件填充放置区 - 异步



我正在尝试用从服务器获得的文件填充我的放置区。我发现这篇文章似乎可以做我想做的,但是似乎我只能在 init 函数中调用这个 addCustomFile 函数,而不是在我从服务器临时收到数据之后(与我正在查看的对象关联的文件列表(。

Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
this.addCustomFile ({ //THIS WORKS
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})
}
}
let imageDropZone = $("#imageDrop").dropzone();
imageDropZone.addCustomFile ({ //THIS DOESN'T WORK - addCustomFile is not a function
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})

关于如何最好地修改它以便我可以在创建放置区后在异步函数中调用它的任何想法?

我能够使用承诺解决这个问题。我必须为承诺定义一个变量,并为数据定义一个变量,这两个变量都在代码的范围内。然后在初始化期间创建承诺,并在我的另一个异步调用中解决它。更新了下面的代码:

var imageLoadDefer; //Variable that will get a promise
var slowLoaded; //Variable that will get loaded with data async
Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
//Create the promise using jQuery
imageLoadDefer =$.Deferred();
//Important: Make sure to put this into a variable that can be used in the following function
var imDrop = this;
imageLoadDefer.always(function(){
//promise is resolved and variable is now populated
imDrop.addCustomFile ({ //THIS WORKS NOW, ASYNC
processing: true,
accepted: true,
name: slowLoaded.name,
size: slowLoaded.size,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, slowLoaded.thumbnail, {
status: "success"
});
});
}
}
let imageDropZone = $("#imageDrop").dropzone();
$.getJSON('images.json', function (data) { 
slowLoaded = data;
imageLoadDefer.resolve(); //data loaded so resolve image promise
}

最新更新