Java script how to pass around an object with event being attached

Viewed 44

I have a custom object that being passed around. I want to show a toast when a workflow is done. I am looking for some thing like

object.addEvent("workflowIsDone", ()=> {
    toast.open();
});

and when the workflow ends:

object.fireEvent("workFlowIsDone")

I was wondering if some one can tell me how to do it in Javascript

2 Answers

You might add a method to your object:

object.workflowIsDone = () => toast.open();

and call it when the workflow ends:

object.workFlowIsDone()

You can produce new events by using const myEvent = new Event('eventName')

And then add a listener to it: element.addEventListener('eventName', function () { // ... })

Also you need to dispatch it: element.dispatchEvent(myEvent)

For passing custom data there's a CustomEvent class that you can use. You can read more about it here

Related