Search code examples
javascriptweb-component

javascript -how to launch an event from a web component, from outside it


I need a solution with this, I am trying to fire an event from within a web-component with the handleEvent, but I am not able:

class MyElement extends HTMLElement {
    connectedCallback() {
        paintElement2(this);
    }

    handleEvent(event) {
        console.log(event.type); // doesn't work
    }
}

customElement.define("my-element", MyElement);

function paintElement2(elementWhoCall) {
    let a = document.createElement("a");
    a.textContent = "click me and launch event inside the caller";
    document.body.appendChild(a);
    a.addEventListener("click", (event) => {
        elementWhoCall.dispatchEvent(new Event("myevent"));
    });
}

Thx!


Solution

  • There are two possible solutions:

    The best in my opinion:

    class MyElement extends HTMLElement {
        connectedCallback() {
            this.addEventListener("myevent", this)
            paintElement2(this);
        }
    
        handleEvent(event) {
            console.log(event.type); 
        }
    }
    
    customElement.define("my-element", MyElement);
    
    function paintElement2(elementWhoCall) {
        let a = document.createElement("a");
        a.textContent = "click me and launch event inside the caller";
        document.body.appendChild(a);
        a.addEventListener("click", (event) => {
            elementWhoCall.dispatchEvent(new Event("myevent"));
        });
    }
    

    The second option:

    class MyElement extends HTMLElement {
        connectedCallback() {
            paintElement2(this);
        }
    
        handleEvent(event) {
            console.log(event.type); // doesn't work
        }
    }
    
    customElement.define("my-element", MyElement);
    
    function paintElement2(elementWhoCall) {
        let a = document.createElement("a");
        a.textContent = "click me and launch event inside the caller";
        document.body.appendChild(a);
        a.addEventListener("click", (event) => {
            elementWhoCall.handleEvent(new Event("myevent"));
        });
    }