The this
pointer is different inside the callback function. So, you need to save it into a different variable. Then, use that variable instead of this
inside your callback. For a Lightning helper, I save it to one called helper
save : function(component) {
// var maxFileSize = 750000;
var fileInput = component.find("file").getElement();
var file = fileInput.files[0];
if (file.size > maxFileSize) {
alert('File size cannot exceed ' + maxFileSize + ' bytes.\n' +
'Selected file size: ' + file.size);
return;
}
var fr = new FileReader();
var helper = this;
fr.onload = function() {
var fileContents = fr.result;
var base64Mark = 'base64,';
var dataStart = fileContents.indexOf(base64Mark) + base64Mark.length;
fileContents = fileContents.substring(dataStart);
alert("WORKING"); //check at this point- alert works
helper.upload(component, file, fileContents);
alert("DID IT WORK?"); // This alert not shown so upload call not working
};
fr.readAsDataURL(file); //fr.onload function triggered from here
},
upload: function(component, file, fileContents)
{ alert("Here"); //NEVER CALLED
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this