问题
I need a little help with FileReader API. Is there any way how to get data from FileReader outside it. I have a "class" with method, where image is read with FileReader and I want to put image data to the class local variable (as shown in following code).
I do know that FileReader works asynchronously and my solution is wrong. Is there any way how to make it work? Thank you.
CanvasState.prototype.addImage = function(inputFile) {
var file = inputFile;
var reader = new FileReader();
reader.onload = this.loadImageData;
reader.readAsDataURL(file);
}
CanvasState.prototype.loadImageData = function(e) {
this.hasImage = true;
this.imageData = e.target.result;
}
回答1:
Try this:
CanvasState.prototype.addImage = function(inputFile) {
var file = inputFile, self = this;
var reader = new FileReader();
reader.onload = function(e) {
self.hasImage = true;
self.imageData = e.target.result;
};
reader.readAsDataURL(file);
}
回答2:
This is an issue with the way this
is set in a function. When you do:
foo.bar();
this
inside bar()
will be foo
. But if you do:
var bar = foo.bar;
bar();
this
will be the global object.
In your case, the problem is that when you set reader.onload
, you are setting it to the function pulled out of the CanvasState prototype. When the reader loads and then calls that function, it is like the example above where the this
will be the global object, and not the same it was inside addImage
.
To fix this, you can use the bind()
method to create a new function will call loadImageData
with the this
you expect.
Basically, change:
...
reader.onload = this.loadImageData;
...
to:
...
reader.onload = this.loadImageData.bind(this);
...
Check out JavaScript Function bind for more info and interactive examples.
来源:https://stackoverflow.com/questions/16177781/how-to-get-data-out-of-filereader