Quiero implementar un sistema de eventos en un objeto js puro que sea similar a los eventos DOM, que se pueden enviar y burbujear del objeto secundario al principal. ¿Puedo usar interfaces existentes como EventTarget o Event para hacer esto? ¿Cuál es la forma correcta de lograr esto?
<!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>Después de buscar un poco, encontré esta respuesta . Todavía usa el árbol DOM para asegurarse de que el evento burbujee de niño a padre. ¿Se puede hacer esto sin usar el árbol DOM?