Javascript - Dispatch event to all objects in a set

332 Views Asked by At

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

There are 1 best solutions below

7
Randy Casburn On

To make your custom event work with Konva Node objects, the Shape subclass has an on method that will allow you to register your listener directly on the shape.

Do this:

class Node{...}

a = new Node(...);
b = new Node(...);
a.shape.on('Yo!', handler);
b.share.on('Yo!', handler);
  // all 4000 shapes

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

// If you only have one handler for every shape's treatment of CustomEvent
for (var node of nodeSet){
     node.shape.on('Yo!', handler);
}

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