vball
vball

Reputation: 389

How do I broadcast an EventCallback to multiple listeners in Blazor WASM?

Conceptually, I am having difficulty finding out how to broadcast an event to multiple components. It seems that the EventCallback property can only be set to one method. Basically, I have a service that runs a method based on window events, and I want multiple different components to be able to "subscribe" to this change.

Even a pointer towards documentation on how to accomplish this would be greatly appreciated

Upvotes: 3

Views: 1419

Answers (1)

Daniel
Daniel

Reputation: 612

I see you found a workable alternative, but I can answer your question directly.

Blazor's EventCallback and EventCallback<T> are wrappers around traditional delegates, and traditional delegates already support exactly what you want to do. Simply add to their invocation list, exactly as if they were an event.

Declare your delegate and add your handlers:

Func<string, Task>? MyDelegate { get; set;} = null;

void InitializeMyDelegate()
{
    MyDelegate += FirstHandler;
    MyDelegate += SecondHandler;
}

If you need to, you can have multiple classes/components subscribe to the delegate as above.

Then pass it to a component as an EventCallback normally:

<SomeComponent MyEvent="MyDelegate">
    // other stuff 
</SomeComponent>

Whenever that instance of SomeComponent calls MyEvent.InvokeAsync(), every handler you added to MyDelegate will be invoked.

Upvotes: 2

Related Questions