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?