What's the benefit of helper class when calling from JS to .NET component instance .NET method in Blazor

Viewed 118

The blazor docs recommends to use helper class when calling from JavaScript to .NET component instance.

The helper class does nothing but delegates to component methods anyway:

public class MessageUpdateInvokeHelper
{
    private Action action;

    public MessageUpdateInvokeHelper(Action action)
    {
        this.action = action;
    }

    [JSInvokable("BlazorSample")]
    public void UpdateMessageCaller()
    {
        action.Invoke();
    }
}
@inject IJSRuntime JS

@code {
    private string message = "Select one of these list item buttons.";
    private MessageUpdateInvokeHelper? messageUpdateInvokeHelper;

    protected override void OnInitialized()
    {
        messageUpdateInvokeHelper = new MessageUpdateInvokeHelper(UpdateMessage);
    }

    private void UpdateMessage()
    {
        message = "UpdateMessage Called!";
        StateHasChanged();
    }
}

Why not just define [JSInvokable] on the component instance?

@code {
    private string message = "Select one of these list item buttons.";

    [JSInvokable("BlazorSample")]
    private void UpdateMessage()
    {
        message = "UpdateMessage Called!";
        StateHasChanged();
    }
}
0 Answers
Related