我对 FileReader.onload()
有一些问题事件:
以下两个代码片段之间得到不同结果的原因是什么?一旦我传递了 object
实例,而不是显式的 this.attachmentIndex
值,我就会得到不同的结果。
1)
fileReader.onload = (function (file, obj) {
return function (evt) {
obj.attachmentIndex // 1
};
})(f, this);
2)
fileReader.onload = (function (file, index) {
return function (evt) {
index // 0
};
})(f, this.attachmentIndex);
关闭 - FileReader.onload()
我面临的另一个问题是,我似乎无法将多个参数传递给我的 FileReader.onload()
事件处理程序。
fileReader.onload = (function (file, one, two) {
return function (evt) {
one // 1
two // undefined
};
})(f, 1, 2);
下面你可以找到整个对象。我不得不做一些丑陋的事情来实现我想要的。我真的希望有更好的方法来达到相同的结果。
function Note() {
this.attachmentOutput = [];
this.attachmentIndex = 0;
this.debugging = false;
this.currentWorkingObject = new NoteObject(helperFn.createGuid());
this.addAttachement = function(files) {
for (var i = 0, f; f = files[i]; i++) {
var fileReader = new FileReader(),
fileReader.onload = (function (file, obj) {
return function (evt) {
var base64File = evt.target.result;
obj["note"].addDataToAttachementObj(obj["index"], { data: base64File })
};
})(f, { note: this, index: this.attachmentIndex});
// Async => reading file
fileReader.readAsDataURL(f);
this.attachmentIndex++
}
var html = app.outputTemplate(this.currentWorkingObject.attachements);
$('.upload-output').html(html);
};
};
函数的触发器:
$(".upload-drop-zone").on('drop', function (e) {
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
app.myCurrentNote.addAttachement(files);
});
最佳答案
I want 0 as a result for the index value in the closure - in the end I got it but just with this ugly workaround. If I don't pass the argument explicitly, then I get 1 and I don't know why.
FileReader
是异步的。 this.attachmentIndex
似乎在
1
// Async => reading file
fileReader.readAsDataURL(f);
this.attachmentIndex++ // <- `this.attachmentIndex` incremented to `1` here
可能在调用 FileReader.onload
事件之前。
关于javascript - FileReader() - 闭包和传递参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547856/