简体   繁体   中英

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

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. The trick is adding to their invocation list before you hand it over for Blazor to convert into an EventCallback .

This is no different from adding handlers to an event:

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

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

If you make it accessible, other classes can also add to the invocation list.

When you are done, simply hand it off to Blazor as normal:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM