zoukankan      html  css  js  c++  java
  • [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);
        });
  • 相关阅读:
    requestAnimationFrame
    react 面试题
    useState使用和原理
    常用网址记录
    .net 学习官网
    centos nginx 设置开启启动
    Asp.Net Core 发布和部署 Linux + Nginx
    SQL Server 执行计划缓存
    SQL Server之索引解析(二)
    SQL Server之索引解析(一)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12463243.html
Copyright © 2011-2022 走看看