我有一个自定义类,可以出于各种目的对其进行扩展,以下代码可以正常工作:
git merge old_branch
(Mousedown和mouseup只是两个示例;我希望能够处理其他鼠标事件,甚至键盘事件。)
是否可以将某些重复的代码移至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");
}
}
超类中?我假设超级类中的eventListener无法引用子类中的函数。
编辑:我应该认为,尽管此示例中的事件处理程序非常相似,但实际上,事件的处理方式可能非常不同,甚至可以忽略。
谢谢!
答案 0 :(得分:1)
在父类中,将侦听器添加到画布,然后在构造函数中,您可以传递侦听器操作。
您可以执行以下操作:
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>