从类中返回数据

我有一个文件丢弃类。 用户丢弃图像(根据需要),然后上传这些图像。

我从我的主课那里打电话给class级:

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 = $(''); // 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); 

http://jsfiddle.net/Nm5vK/2/