I have the below code (simplified from what I am actually doing). Essentially, I have a class instance with some state and a method that is called by an event listener, which gets a file from the user and uploads it. I have have out how to bind this from within the method to the upload callback, but I can't work out how I would bind the state to the method for when it is called by the event listener. I would like to do this without using ES6 class syntax, because I want to learn prototypes properly before moving on to class syntax.
export default function State() {
this.message = "hello";
}
State.prototype.uploadMethod = function (e) {
var reader = new FileReader();
reader.onload = upload.bind(this);
function upload() {
var base64image = reader.result;
fetch("/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: this.message, image: base64image }),
});
}
reader.readAsDataURL(e.target.files[0]);
};
const state = new State();
const button = document.querySelector("button");
button.addEventListener("click", uploadMethod);