简体   繁体   中英

Blazor: intercept an EventCallback to add some code

In my Blazor WebAssembly application, I use a lot the TelerikGrid component, provided by Telerik Kendo, but my question could be the same with another component. I need to execute some code at the end of the execution of the handler of the "OnRead" EventCallback of TelerikGrid, as bellow:

protected async Task OnReadHandler(GridReadEventArgs args)
{
    args.Data = _myClient.GetData();  //some code

    // This line is the one I need to repeat accros all handlers of OnRead in my application
    await JSRuntime.InvokeVoidAsync("attachAllGridCells");
}

I do not know if Blazor can achieve my request. In addition, the component TelerikGrid cannot be modified, as it is from a third-party. I've tried something, with no good result:

  • Create a component which extend TelerikGrid, and trying to somehow override OnRead. But as it is an EventCallback, and not a method, I cannot do that easily:
public partial class CustomTelerikGrid<T> : TelerikGrid<T>
{
    [Parameter]
    public new EventCallback<GridReadEventArgs> OnRead { get; set; }

    async Task TestAsync()
    {
        await this.OnRead.InvokeAsync(); // access to my "new" eventcallback
        await base.OnRead.InvokeAsync(); // access to the "original" eventcallback
    }
}

Is there way I can achieve that? I believe not really with my knowledge of Blazor, but maybe someone can have an idea, thanks in advance for any help.

We have a grid component in our project that extends TelerikGrid . We made class TelerikGridSettings with parameters from base Telerik Grid which we use in our grids across our project like that:

public partial class TelerikGridSettings<TItem> : BaseComponent
{
    [Parameter]
    public IEnumerable<TItem> Data { get; set; }

    [Parameter]
    public decimal RowHeight { get; set; }

    [Parameter]
    public RenderFragment GridColumns { get; set; }

    [Parameter]
    public EventCallback<GridReadEventArgs> OnRead { get; set; }
    
    /// etc
}

Then in your custom GridComponent you use TelerikGrid and fill parameters like that, and also insert your custom OnReadHandler :

<TelerikGrid TItem="TItem"
            Data=@Data
            RowHeight=@RowHeight
            GridColumns=@GridColumns
            OnRead=@OnReadHandler
            // etc />

In your OnReadHandler you will invoke TelerikGrid common OnRead event callback and after that use your JS method:

private async ValueTask OnReadHandler()
{
    await OnRead.InvokeAsync();

    // your js method
}

Then you can use your GridComponent exactly as you use TelerikGrid right now.

Hope this helps. Also this approach will give you more flexibility in customizing your grid.

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