Tom Crosman
Tom Crosman

Reputation: 1285

Passing a function with parameters to a child component

I'm writing blazor component wrappers for some of my favorite Javascript plugins using Javascript interop.

My parent component has this function:

async Task<IEnumerable<DpEvent>> GetEvents(DateRange dateRange)
{
    return await EventManager.GetEvents().Where(e => e.StartDate >= dateRange.StartDate).Where(e => e.EndDate <= dateRange.EndDate).ToListAsync();
}

and my childcomponent has this parameter:

[Parameter] public Func<DateRange, Task<IEnumerable<DpEvent>>> GetEvents { get; set; }

What must I do to pass my GetEvents Method to my child component like so:

<ChildComponent GetEvents="GetEvents"></ChildComponent>

Upvotes: 1

Views: 1420

Answers (1)

Tom Crosman
Tom Crosman

Reputation: 1285

I was able to solve this problem by creating a custom delegate for my callback.

Function I wanted to pass to child component:

async Task<IEnumerable<DpEvent>> GetEvents(DateRange dateRange)
{
    return await EventManager.GetEvents().Where(e => e.StartDate >= dateRange.StartDate).Where(e => e.EndDate <= dateRange.EndDate).ToListAsync();
}

Definition and Declaration of my delegates:

public delegate Task<IEnumerable<DpEvent>> GetEventsDelegate(DateRange dateRange);
public GetEventsDelegate GetEventsCallBack;

Assigning my delegates to my function:

protected override async Task OnInitializedAsync()
{
    GetEventsCallBack = GetEvents;
}

Passing my delegate to my child component:

<ChildComponent GetEvents="GetEventsCallBack"></ChildComponent>

My Parameter on my Child Component:

[Parameter] public Func<DateRange, Task<IEnumerable<DpEvent>>> GetEvents { get; set; }

And finally, my child component can use the delegate:

IEnumerable<DpEvent> dpEvents = await GetEvents.Invoke(dateRange);

Upvotes: 1

Related Questions