I was wondering if we call a function directly, why should we use event callback?For example, I use an event callback to set the colour of a component from the child to the parent.
This is the child component:
<button @onclick="OnButtonClick">Click me</button>@code { [Parameter] public EventCallback<string> OnColorChange { get; set; } private async Task OnButtonClick() { await OnColorChange.InvokeAsync("new-color"); }}This is parent component:
<ChildComponent OnColorChange="HandleColorChange" /> @code { private string currentColorClass = "default-color"; private void HandleColorChange(string newColorClass) { currentColorClass = newColorClass; }}So, instead of the definition for HandleColorChange as a public static method, just call it directly, like this:
ParentComponent.HandleColorChange("new-color");This isn't the only problem, we use JS interop to call C# functions, although we can handle all of these by calling them directly.The final question is, when should a method be called directly and when shouldn't it?