0

I am trying to access a method from my "class" from a method called asynchronously by the code.

Here is my reduced class:

function FileProcessor(file, callback) {    
    this.file = file;
    this.callback = callback;
}

FileProcessor.prototype.readerOnload = function(e) {
    this.callback(e.target.result);
};

FileProcessor.prototype.process = function() {
    var reader = new FileReader();
    reader.onload = this.readerOnload;

    if (this.file.type == 'text/xml') {
        reader.readAsText(this.file);
    }
};

My cal to this.callback works from the constructor FileProcess, works from process(), but doesn't work from readerOnload. I get:

Uncaught TypeError: undefined is not a function

Any idea what I am doing wrong?

Thanks

Carlo
  • 380
  • 1
  • 12

1 Answers1

1

I suppose your readerOnLoad function is called in a different context than you expect, and you end up with a this value which is not an instance of FileProcessor.

Try this:

reader.onload = this.readerOnload.bind(this);

Or, if you must support older browsers:

var self = this;
reader.onload = function(e) { self.readerOnLoad(e); };
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158