Javascript – Dispatch event to all objects in a set

How do I dispatch a custom event to all the custom objects in my set?

class Node{...}

a = new Node(...);
b = new Node(...);

var nodeSet = new Set(...);
let myEvent = new CustomEvent(...);

for (var node of nodeSet){
     node.shape.dispatchEvent(myEvent); 
}

Node.shape is a Konva Shape

Please keep the replies easy to understand since I am a beginner in Javascript, thanks.

1 thought on “Javascript – Dispatch event to all objects in a set”

  1. This is one solution:

    1. create a global fantom div to dispatch the event to
    2. create an event listener on that div for custom event
    3. dispatch the event to that ‘div’
    4. Use a Node class method to deal with the shape.
    const recipient = new EventTarget();
    class Node {
      constructor() {
        recipient.addEventListener('yo!', this.shaper.bind(this));
      }
      shaper() {
        alert('do something with shape');
      }
    }
    a = new Node();
    b = new Node();
    
    let myEvent = new CustomEvent('yo!');
    recipient.dispatchEvent(myEvent);
    Reply

Leave a Comment