Can a child class respond to events captured by it

2019-08-20 05:01发布

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!

1条回答
Lonely孤独者°
2楼-- · 2019-08-20 05:19

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:

class Inator {
    constructor(whichCanvas, mouseDown, mouseUp) {
        this.myCanvas = whichCanvas;
        this.myCanvas.addEventListener("mousedown", mouseDown);
        this.myCanvas.addEventListener("mouseup", mouseUp);
    }
}

class Ballgowninator extends Inator {
    constructor(whichCanvas) {
        super(whichCanvas, (e) => 
        console.log("ballgowninator mousedown"), (e) => 
        console.log("ballgowninator mouseup"));
    }    
}

class Yodelinator extends Inator {
    constructor(whichCanvas) {
        super(whichCanvas, (e) => 
        console.log("yodelinator mousedown"), (e) => 
        console.log("yodelinator mouseup"));
       
    }
   
}

const canvas = document.getElementById('canvas');
const b = new Ballgowninator(canvas);
const y = new Yodelinator(canvas);
<h1 id="canvas">CLICK ME!!!</h1>

查看更多
登录 后发表回答