I have a custom class which I am extending for various purposes, and the following code is working just fine:
class Inator {
constructor(whichCanvas) {
this.myCanvas = whichCanvas;
}
}
class Ballgowninator extends Inator {
constructor(whichCanvas) {
super(whichCanvas);
this.myCanvas.addEventListener("mousedown",this.handleMouseDown);
this.myCanvas.addEventListener("mouseup",this.handleMouseUp);
}
handleMouseDown(e) {
alert("ballgowninator mousedown");
}
handleMouseUp(e) {
alert("ballgowninator mouseup");
}
}
class Yodelinator extends Inator {
constructor(whichCanvas) {
super(whichCanvas);
this.myCanvas.addEventListener("mousedown",this.handleMouseDown);
this.myCanvas.addEventListener("mouseup",this.handleMouseUp);
}
handleMouseDown(e) {
alert("yodelinator mousedown");
}
handleMouseUp(e) {
alert("yodelinator mouseup");
}
}
(Mousedown and mouseup are just two examples; I want to be able to handle other mouse events and even keyboard events as well.)
Is there a way I can move some of this duplicated code into the Inator
superclass? I am assuming that there is no way for an eventListener in the super to refer to a function in the child class.
EDIT: I should that while the event handlers are very similar in this example, in practice the events might be handled very differently, or even ignored.
Thanks!
In your parent class add the listener to your canvas, and in the constructor, you can pass the listener actions.
You can do something like this: