JSFiddle - React, Tailwind, and code Playground

by ChangJoo Park

HTML

<template id="my-counter">
  <button onClick="callMinus()">-</button>
  <strong>1</strong>
  <button onClick="callPlus()">+</button>
  
  <script>
    var btnEvent = document.createEvent("MouseEvent");
    btnEvent.initEvent('oncomponentbtn', true, true);
    var callMinus = function() {
      window.dispatchEvent(btnEvent);
    };
    var callPlus = function() {
	    console.log('plus')
      window.dispatchEvent(btnEvent);
    };
  </script>
</template>

<my-counter></my-counter>

JavaScript

class MyCounter extends HTMLElement {

  // Can define constructor arguments if you wish.
  constructor() {
    // If you define a constructor, always call super() first!
    // This is specific to CE and required by the spec.
    super();
    const root = this.createShadowRoot();
    const template = document.querySelector('#my-counter');
    const clone = document.importNode(template.content, true);
    root.appendChild(clone);
  }
}

customElements.define('my-counter', MyCounter);

window.addEventListener('oncomponentbtn', function (event) {
    console.log(event);
    alert(event);
});