Razor Component Callbacks

To communicate from a child razor component to the component that references it (the parent), pass the name of the callback function to the child component in much the same way you pass parameters. Think of the callback function as a delegate you pass to the child as a parameter.

(In this case, the child component lists chess players and allows you to select one to challenge. The callback in the parent component receives the player being challenged.)

// PARENT COMPONENT 

<chess.Components.PlayersComponent 
     PlayersOnline="PlayersOnline"                <<< the data we loop through
     ChallengeAsyncCallback="ChallengeAsync" >    <<< the callback function
</chess.Components.PlayersComponent>

// The callback function referred to in the component HTML
public static async Task ChallengeAsync(Models.Player PlayerToChallenge)
    {
        if (ThisPlayer.PlayerID != PlayerToChallenge.PlayerID)
        {
            System.Threading.CancellationToken cancellationToken = default;
            // will create game record
            await PlayChess._hub.InvokeAsync("startgame", ThisPlayer.Name, PlayerToChallenge.Name, cancellationToken);
        }

    }
// CHILD COMPONENT
// Create an event handler in the child razor component 
// This button is in a for-next loop. Each time through, @p is a "Models.Player"
//
<button class="btn btn-sm btn-outline-primary" 
         @onclick="@(() => ChallengeAsyncCallback.InvokeAsync(@p))">Challenge</button>

// The type of the event callback parameter is Models.Player.
// ChallengeAsync is the name of the HTML attribute that holds the name of the 
// function to call on the parent componennt.
// <Models.Player> indicates that the callback function in the parent component 
// takes a Models.Player as an argument. 
[Parameter]
public EventCallback<Models.Player> ChallengeAsyncCallback { get; set; }


The name of the parent component’s function name (the callback) is given in the HTML component as an attribute. Above, ChallengeAsyncCallback(1)=”ChallengeAsync”(2) means the ChallengeAsyncCallback(1) property in the child component (the EventCallback declaration, which uses the same name as the attribute) will point to the ChallengeAsync(2) function in the parent.

If the callback function takes an argument, the declaration of the callback in the child component can be given a type of the argument, thus:

[Parameter]
public EventCallback<Models.Player> ChallengeAsyncCallback { get; set; }

means that the parent component’s callback function accepts an argument of type Models.Player. It appears as though only one callback argument is allowed.

For more on component communication, see https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/

You may also like...