aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Blazor.registerFunction error when navigating between pages

Open dlr1 opened this issue 8 years ago • 1 comments

Created a project using dotnet new blazor -o BlazorApp2

updated the code in Counter.cshtml to the following

@page "/counter"
@using Microsoft.AspNetCore.Blazor.Browser.Interop
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button @onclick(IncrementCount)>Click me</button>

<script>   
    function func2(){
        console.log("func called");
    }
    Blazor.registerFunction('func1', (data) => {
        console.dir("counter value is --" + data);    
         func2();
        return true;
    });
</script>

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
        RegisteredFunction.Invoke<bool>("func1", currentCount);
    }
}

when you navigate back and forth between pages I get Uncaught Error: A function with the identifier 'func1' has already been registered.

dlr1 avatar Mar 30 '18 13:03 dlr1

You shouldn't be calling registerFunction from inside a component's render flow (i.e., inside its Razor markup). If you do that, then it will get called multiple times if the component is rendered multiple times, and you will get errors like this. More generally, I'm unconvinced that you should ever have a <script> tag inside a Blazor component's markup - that's well outside the normal rendering pattern.

The intended way to use registerFunction is from inside your index.html file, or a <script> (i.e., .js file) loaded by it. Just put that directly below the <script type='blazor-boot'></script> and it will load at the correct time and only execute once. Much simpler!

SteveSandersonMS avatar Mar 30 '18 16:03 SteveSandersonMS