[removed] how adding event handler inside a class with a class-method as the callback?

后端 未结 2 1651
有刺的猬
有刺的猬 2020-12-05 08:20

How do i add an event handler inside a class with a class-method as the callback ???

move over here
2条回答
  •  天涯浪人
    2020-12-05 08:42

    You can actually return the object as an EventListener callback, this way JS will search for an handleEvent method in the class and execute accordingly :

    var myInstance = new myClass;
    myInstance.addEventListener("mousedown",myInstance);
    
    //To remove the event you can follow the same pattern
    myInstance.removeEventListener("mousedown",myInstance);
    

    You have to construct your class this way :

    Class myClass
    
    constructor(){
         //Whatever this is supposed to do.
         //You can also add events listener within the class this way :
         this.addEventListener("mousedown",this);
    }
    
    mouseDownEvent(e)(){
         //Some action related to the mouse down event (e)
         console.log(e.target);
    }
    mouseMoveEvent(e)(){
         //Some action related to the mouse move event (e)
    }
    mouseUpEvent(e)(){
         //Some action related to the mouse up event (e)
    }
    
    handleEvent(e) {
        switch(e.type) {
            case "mousedown":
                this.mouseDownEvent(e);
            break;
            case "mousemove":
                this.mouseMoveEvent(e);
            break;
            case "mouseup":
                this.mouseUpEvent(e);
            break;
        }
    }
    

    Sources :

    https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38

    https://www.thecssninja.com/javascript/handleevent

    https://metafizzy.co/blog/this-in-event-listeners/

    I find this method clearer, also while declaring events inside the class this is pretty explicit. Hope I helped someone.

提交回复
热议问题