简体   繁体   中英

Blazor - Problem with EventCallback of multiple instances of same component

I'm having some problems with my C# Blazor App.

I've got a simple component that runs a js file, the js file after some operations will call the UpdateLocalizationData method. The method will populate the Place object and invoke the EventCallback. This is the component AddressComponent :

@page "/AddressComponent"
@inject IJSRuntime JSRuntime


<input id="@Id" class="form-control" name="address" placeholder="Search address" />

@code {

    private static Place PlaceToUse { get; set; } = new Place();

    [Parameter] 
    public EventCallback<Place> OnPlaceSelected { get; set; }

    [Parameter] 
    public string Id { get; set; }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("initAutocomplete", DotNetObjectReference.Create(this), Id);
        }
    }

    [JSInvokable]
    public void UpdateLocalizationData(string lat, string lon)
    {    
        PlaceToUse.Id = Guid.NewGuid();
        PlaceToUse.Latitudine = lat;
        PlaceToUse.Longitudine = lon;

        OnPlaceSelected.InvokeAsync(PlaceToUse);
    }
}

Then i call the component in two different razor components. PageA.razor :

<AddressComponent OnPlaceSelected="HandlePlace" Id="addressA"></AddressComponent>

@code{
    private ItemA ItemATest { get; set; } = new ItemA()
    private void HandlePlace(Place place)
    {
        ItemATest.Place = place;
    }
}

PageB.razor :

<AddressComponent OnPlaceSelected="HandlePlace" Id="addressB"></AddressComponent>

@code{
    private ItemB ItemBTest { get; set; } = new ItemB()
    private void HandlePlace(Place place)
    {
        ItemBTest.Place = place;
    }
}

Both components (PageA and PageB) are then called in the main page.

My problem is that when the EventCallback method of the AddressComponent in PageA is triggered, it triggers the method HandlePlace of PageB . From what i've understood, the parameters of the component (such as the EventCallback) are getting replaced everytime the component is instantiated, thus resulting in the Eventcallback of only the last component being triggered. How can i solve this? Am i using the wrong approach?

The problem is inside the JS method that you call using InvokeVoidAsync. The first call sets the instance to PageA, the second call overwrites the instance to PageB. So all calls made from the JS function will be done on PageB

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