子类可以响应其上级捕获的事件吗? [英] Can a child class respond to events captured by its super?

查看:229
本文介绍了子类可以响应其上级捕获的事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,可以出于各种目的对其进行扩展,以下代码可以正常工作:

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

(Mousedown and mouseup are just two examples; I want to be able to handle other mouse events and even keyboard events as well.)

是否可以将某些重复的代码移到Inator超类中?我假设超级类中的eventListener无法引用子类中的函数.

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.

我应该认为,尽管该示例中的事件处理程序非常相似,但实际上,事件的处理方式可能非常不同,甚至可以忽略.

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.

谢谢!

推荐答案

在父类中,将侦听器添加到画布,在构造函数中,您可以传递侦听器操作.

In your parent class add the listener to your canvas, and in the constructor, you can pass the listener actions.

您可以执行以下操作:

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>

这篇关于子类可以响应其上级捕获的事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆