0

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.

3 Answers 3

2

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) { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

In 15 years of development, I've never known that the default parameters are still passed, but at the end of the bind! You're my hero.
1

Just assign a different function to reader.onloadend.

reader.onloadend = function(evt) {
    readCompleted(evt, currentFileType);
};

Comments

0

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... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.