[Web component] Using Custom Events as a web component API

Learn how to use custom events to expose internal events from withing a web component.

复制代码
   class MyWelcome extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = `
                <h1>Welcome <span id="username">Developer</span></h1>
                <div><input id="usernameField"></div><br/>
                <div><button id="changeUsername">Change username</button></div>
        `;

        this.userName = this.shadowRoot.querySelector('#username');
        this.input = this.shadowRoot.querySelector('#usernameField');
        this.submitButton = this.shadowRoot.querySelector('#changeUsername');

        this.init();
      }

      init() {
          this.submitButton.addEventListener('click', () => {
            this.userName.innerText = this.input.value;
            this.emitExternalEvent('username-changed', this.input.value);
          });
      }

      emitExternalEvent(eventName, payload) {
          const customEvent = new CustomEvent(eventName, {detail: payload});
          this.dispatchEvent(customEvent);
      }
    }

    customElements.define('my-welcome', MyWelcome);
    const myWelcomeComponent = document.createElement('my-welcome');
    document.body.appendChild(myWelcomeComponent);
    myWelcomeComponent.addEventListener('username-changed', (event) => {
        console.log(event.detail);
    });
复制代码

 

posted @   Zhentiw  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-11 [Algorithm] Tower Hopper Problem
2019-03-11 [Algorithm] Given the root to a binary tree, return the deepest node
2018-03-11 [HTML5] Text Alternatives
2018-03-11 [HTML5] Semantics for accessibility
2016-03-11 [RxJS] Logging a Stream with do()
2016-03-11 [RxJS] Handling a Complete Stream with Reduce
2016-03-11 [RxJS] Completing a Stream with TakeWhile
点击右上角即可分享
微信分享提示