Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

javascript - Fire events in a web-component

I am trying to raise events out of a webcomponent, but it does.

<my-component id="xyz" bez="hallo" hello="myScript()"></my-component>
<script>
    xyz.addEventListener("hello", function(event) {
        console.log(event.detail.name);
    });
</script>

Neither the html-tag "hello" does raise the event, nor the event-listener does.

The web component looks like this:

var button=document.createElement("button");
button.innerHTML=cap;
button.addEventListener('click', () => {
    console.log("click");
        
    button.dispatchEvent(new CustomEvent("hello", {
        detail: { name: "John" }
    }));
});
    
shadow.appendChild(button);

Can anyone help me please to find the mistake? Thanks a lot.

Code-Fiddle here: https://jsfiddle.net/b43uqsLp/2/

question from:https://stackoverflow.com/questions/65890122/fire-events-in-a-web-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem occurs because of the Shadow DOM (try to inspect your component and you will see what I mean): enter image description here

Good news, it's really simple to fix - just propagate the event across the shadow DOM into the regular DOM via composed: true property in your CustomEvent's options:

button.dispatchEvent(new CustomEvent("hello", {
    detail: { name: "John" },
    composed: true // Like this
}));

Here is JSFIDDLE.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...