Reputation: 131
I have a pretty simple function that is reading a file with HTML 5 FileReader:
var reader = new FileReader();
var currentFileType = file.type;
reader.onloadend = readCompleted;
reader.onerror = fail;
reader.readAsArrayBuffer(file);
and the readCompleted callback function looks like this:
function readCompleted(evt) {
if (evt.target.readyState != FileReader.DONE) {
return;
}
// The binary data is the result.
var requestData = evt.target.result;
// SOME MORE CODE HERE
}
Thing is that 'evt' parameter is passed by default. How can I pass one additional parameter to this callback function in order to have currentFileType variable available? I want this function signature to look like this: function readCompleted(evt, fileType) {//code here}
and pass somehow currentFileType to it.
Upvotes: 0
Views: 1361
Reputation: 439
You can write like this,
var reader = new FileReader();
var currentFileType = file.type;
reader.onloadend = function(evt){
readCompleted(evt,currentFileType);
};
reader.onerror = fail;
The readCompleted will look like this,
function readCompleted(evt,ft) { //code... }
Upvotes: 0
Reputation: 10675
You can use Function.bind
to bind an argument to the function before assigning it to onloadend
.
For example:
var a = function() { console.log(arguments); }
var b = a.bind(null, 123)
b('abc') // -> [123, "abc"]
In your case, it would be:
reader.onloadend = readCompleted.bind(null, file.type);
and readCompleted
should have the following signature:
function readCompleted(fileType, evt) { ... }
Upvotes: 2
Reputation: 32511
Just assign a different function to reader.onloadend
.
reader.onloadend = function(evt) {
readCompleted(evt, currentFileType);
};
Upvotes: 1