i was wondering if we call a function directly, why should we use event call back ? for example i use event callback to set color of a component from child to parent
this is 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");
}
}
and this is parent component
<ChildComponent OnColorChange="HandleColorChange" />
@code {
private string currentColorClass = "default-color";
private void HandleColorChange(string newColorClass)
{
currentColorClass = newColorClass;
}
}
so insted of all of these define HandleColorChange as public static and we can just call it directly like this
ParentComponent.HandleColorChange("new-color");
and this isn't only problem , we use js interop to call c# function , although we can handle all of these by calling it directly, and the final question is : when we can handle by this way and when we shouldn't
It's bad because:
So:
when we can handle by this way and when we shouldn't
Never do it this way, which should be apparent from the comments.
You're creating a single use component for a very specific use case. You might as well forget the component and just create a render fragment you can use in the parent component. That way you forgo all the expense of a component.
In the end it's your code, so your decision.
An important point to understand is you don't control the creation, lifecycle or disposal of components. That's the responsibility of the Renderer.