child class 可以响应其超级捕获的事件吗?

Can a child class respond to events captured by its super?

我有一个自定义 class,我正在为各种目的对其进行扩展,下面的代码工作正常:

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 和 mouseup 只是两个示例;我希望能够处理其他鼠标事件,甚至键盘事件。)

有什么方法可以将一些重复代码移动到 Inator superclass 中吗?我假设 super 中的 eventListener 无法引用 child class.

中的函数

编辑:虽然本例中的事件处理程序非常相似,但实际上事件的处理方式可能非常不同,甚至被忽略。

谢谢!

在您的父级 class 中将侦听器添加到您的 canvas,并在构造函数中,您可以传递侦听器操作。

你可以这样做:

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>