Example JSFiddle here
The above fiddle is a stripped down version of my code just to highlight the issue (try dragging and dropping a file into the window). Basically, webkitGetAsEntry().file() isn't letting me write to anything outside its scope, however, if you drag a file and then manually do console.log(fileList) (however, jsfiddle blocks this) it works fine. Any help would be appreciated, thanks!
upload.js
function Upload() {
_this = this;
this.fileList = 'no file';
this.fire = function(droppedFiles) {
for(i = 0; i< droppedFiles.length; i++) {
this.buildFileSource(droppedFiles[i].webkitGetAsEntry());
}
//This returns the original string
console.log(this.fileList);
}
this.buildFileSource = function(item, path) {
if(item.isFile) {
item.file(function(file) {
_this.fileList = 'file';
//This works as expected
console.log(_this.fileList);
} );
}
};
}
//Event listeners for dragging
$(document).ready(function() {
window.addEventListener("dragenter", function(e) {
event.stopPropagation();
event.preventDefault();
return false;
}, false);
window.addEventListener("dragover", function(e) {
event.stopPropagation();
event.preventDefault();
return false;
}, false);
window.addEventListener("dragleave", function(e) {
event.stopPropagation();
event.preventDefault();
return false;
}, false);
window.addEventListener("drop", function(e) {
e.stopPropagation();
e.preventDefault();
upload = new Upload;
upload.fire(e.dataTransfer.items);
return false;
}, false);
});
console.log(_this.fileList); in your fire function is being invoked before fileList is being modified in the buildFileSource method. This is due to the fact that the file function on a FileEntry (your item variable) is an asynchronous one. In effect, each call to buildFileSource is also asynchronous. Seek out more details on the Entry interface and it's two children: FileEntry and DirectoryEntry on MDN.
Note that use of the webkitGetAsEntry method means that your code will only work on Chrome 21+ as this method is very specific to Chrome (due to the prefix) and the underlying concepts (Entry objects) belong to the Filesystem API, which only Chrome 21+ supports at this time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With