rustyBucketBay
rustyBucketBay

Reputation: 4561

Create and dispatch events javascript. Code execution simple delegation

Comming from a c# background, I just want to create an event in a certain point of my code, soas to be dispatched elsewere, meaning that if in some part of the code there has been a subscription, this delegate function is called.

So I tried to do:

function myFunction() {
    console.log("delegated call achieved!");
}

const myEvent = new Event('onMyConditionIsMet', myFunction, false);  

//at this point the program the subscription takes place
function whatever1() { 
    //...not meaningfull code
    myEvent.addEventListener('onMyConditionIsMet');
    //myEvent += myFunction; c# way subscription in case it makes sense 
}  

//at this point in the program, event subscription is checked and  
//delegate func run in case there has been a subscription
function whatever2() { 
    //...not meaningfull code
    myEvent?.invoke(); // ?.invoke(); would be the c# way to do it. 
}

All the examples I found are related to DOM events, but my case would be for events I create myself, think these are called synthetic events. Another assumption I make in this question is that there would be no arguments in the delegate call function, so, just to be clear with the naming, it would be a delegate with no arguments. Just pointing this because in c# events are just delegate funcs with no arguments, so a specific type of delegate. Not sure if this works the same way in Javscript.

What would be the approach to do this? (Meaning creating a simple event instance, subscribing, and executing the delegated code if there is any subscription)?

Upvotes: 1

Views: 187

Answers (1)

odin
odin

Reputation: 11

I think the functionality you are looking for can be best obtained by using OOP/Classes.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#prototype_methods

Edit: see this also - "event" is deprecated, what should be used instead?

Upvotes: 1

Related Questions