Thanks to tmdesigned’s comment; .bind is the way to go:
class CanvasThing {
constructor(whichCanvas) {
this.boundResize = this.handleResize.bind(this);
window.addEventListener("resize", this.boundResize, false);
...
}
handleResize() {
this.recalculateStuff();
}
}
This allows the wrapper to be completely self-contained and elegant.
I have an canvas wrapper class that needs to run some code when it is resized to be fully responsive. Of course, HTMLCanvasElement doesn’t have a resize event; only the window does. My code looks like this:
class CanvasThing {
constructor(whichCanvas) {
...
}
handleResize() {
this.recalculateStuff();
}
}
var foo = new CanvasThing(document.getElementFromID("bar"));
Now, I’d love to put this in the constructor of my class to make everything self-contained:
window.addEventListener("resize", this.handleResize, false);
But when it calls handleResize, this
is set to the window, not the instance, so handleResize()
won’t work because it can’t access any of the other methods in the class.
Okay, fine, I’ll do this on the global level after initializing foo
:
window.addEventListener("resize", foo.handleResize, false);
But still this
is pointing to the window, so there’s no easy way to access the instance of my class.
Sure, I can hardwire this in to my surrounding code by having the resize event iterate through all the class instances on the page and fire their resize events, but that seems so inelegant. Setting up a timer to be constantly running to check to see if the canvas has been resized seems even more so.
Is there a modern way to handle this sort of thing to make my wrapper object as self-contained as possible?
I hadn’t… that works! I’ve never used .bind before. Thanks for the tip!
Happy to help, TobyRush.