I want a class that saves the resolution from an image that has to be loaded first. It will print Width = undefined
. The problem is of course that the print function is called before the callback function gets called. After I wait a decent time it will print Width = 20
. I am also not sure if its valid to save this
to originalThis
and pass it to the callback function. How should the code look like so that it works without a random waiting time? I think this is a scenario where you work with Promises?
class MarkerSize {
markerWidth;
markerHeight;
constructor(url) {
this.getMeta(url, this.saveData);
}
getMeta(url, callback) {
let img = new Image();
img.src = url;
let originalThis = this;
img.onload = function () {
callback.call(originalThis, this.width, this.height);
};
}
saveData(width, height) {
this.markerWidth = width;
this.markerHeight = height;
}
printSize() {
console.log(`Width = ${this.markerWidth}`);
}
}
let myMarker = new MarkerSize(
'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
);
myMarker.printSize(); //prints Width = undefined
//Here, I use a timeout function to wait for the image. I know this is really bad style.
setTimeout(function () {
myMarker.printSize(); //prints Width = 20
}, 3000);