3

I want to implement event system on pure js object that similar to the DOM events, which can be dispatched and bubbling from child to parent object. Can I use existing interfaces like EventTarget or Event to do this? What is the correct way to achieve this?

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Preview Pro</title>
</head>

<body>
  <div id="app"></div>
  <script>
    class body extends EventTarget {
      constructor(name, parent) {
        super();
        this.name = name;
        this.type = 'body';
        this.parentNode = parent;
      }
    };

    class hand extends body {
      constructor(name, parent) {
        super(name, parent);
        this.type = 'hand';
      }
    }

    class finger extends body {
      constructor(name, parent) {
        super(name, parent);
        this.type = 'finger';
      }
    }

    var human = new body('stanley');
    var left_hand = new hand('left_hand', human);
    var thumb = new finger('thumb', left_hand);
    left_hand.addEventListener('touch', function (e) {
      // bubbling
      console.log(e)
    });

    thumb.addEventListener('touch', function (e) {
      // target
      console.log(e)
    });

    thumb.dispatchEvent(new Event('touch', {bubbles: true}));
  </script>
</body>

</html>

After a little bit of searching, I found this answer. It still use DOM tree to make sure Event bubble throuth child to parent. Can this be done without using DOM tree?

liyuqihxc
  • 41
  • 2
  • check this: https://labs.k.io/creating-a-simple-custom-event-system-in-javascript/ – Khalil Dec 26 '21 at 07:06
  • @Khalil yes, this can certainly do the job if I add the bubbling function to it. but how can I do this with interfaces provided by the js runtime, like Event or EventTarget? – liyuqihxc Dec 26 '21 at 07:30

0 Answers0