代码之家  ›  专栏  ›  技术社区  ›  TobyRush

子类能否响应其超级类捕获的事件?

  •  0
  • TobyRush  · 技术社区  · 5 年前

    我有一个自定义类,它是为各种目的而扩展的,下面的代码工作得很好:

    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 超类?我假设super中的eventListener无法引用子类中的函数。

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

    谢谢!

    1 回复  |  直到 5 年前
        1
  •  1
  •   F.bernal    5 年前

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

    你可以这样做:

    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>