我有一个文件放置类。用户将图像放入(任意数量),然后上传。
我从我的主类中调用该类:
this.fileDrop = new lx.FileDrop();
这是类(class):
(function(){
"use strict";
var FileDrop = function() {
this.init();
};
p.init = function() {
this._initEvents();
};
p._initEvents = function() {
$(window).on('drop', this.onDrop.bind(this)).on('dragover', this.onDragOver);
};
p.onDrop = function(e) {
e.preventDefault();
var self = this;
var files = e.originalEvent.dataTransfer.files;
$.each(files, function(index, file){
self.readFile(file).done(function(data) {
//how to return the data?
});
});
};
p.onDragOver = function(e) {
e.preventDefault();
};
p.readFile = function(file) {
var fileReader = new FileReader();
var deferred = $.Deferred();
fileReader.onload = function(event) {
deferred.resolve(event.target.result);
};
fileReader.onerror = function() {
deferred.reject(this);
};
fileReader.readAsDataURL(file);
return deferred.promise();
};
lx.FileDrop = FileDrop;
}(window));
我的问题涉及将图像数据返回到主类。我怎样才能返回?我如何存储它 - 我希望将返回到主类数组中的所有内容存储起来。上传多个图像时这将如何工作。会进行某种延期工作吗?
最佳答案
像这样怎么样:
var dfd = $.Deferred(),
images = [];
$.each(files, function(index, file){
self.readFile(file).done(function(data) {
dfd.progress(data);
images.push(data);
if(files.length === ++index)
dfd.resolve(images);
}).fail(dfd.reject);
});
在任何你喜欢的地方处理延迟对象:
dfd.progress(function(file){
console.log('file successfully uploaded', file);
}).done(function(images){
console.log('all files successfully uploaded', images);
}).fail(function(){
console.log('something went wrong while uploading an image');
});
另一个例子:
function FileDrop(){
this.uploadCount = 0;
this.images = [];
}
FileDrop.prototype.getImages = function(){
var dfd = $.Deferred(),
size = 3,
that = this;
for(var i = 0; i < size; i++){
this.getImage(i*500, function(image){
var dummyImage = $('<img/>');
// should be 'image' from the callback in your case
that.images.push(dummyImage);
dfd.notify(dummyImage);
if(that.uploadCount === size){
dfd.resolve(that.images);
}
});
}
return dfd.promise();
};
FileDrop.prototype.getImage = function(timeout, callback){
var that = this;
setTimeout(function(){
that.uploadCount++;
callback();
}, timeout);
};
var fd = new FileDrop();
fd.getImages().progress(function(image){
console.log('progress', image);
}).done(function(imageArray){
// preferred way:
//access the array when you know it's complete in the callback
console.log('done', imageArray);
});
setTimeout(function(){
// I think this is what you asked for, however, you must make an
// assumption when the images are completed, which is a bad idea
console.log(fd.images);
}, 2000);
关于javascript - 从类返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24034622/