1
votes

I have a situation where I am listening for scroll events in JS on the page, when the scroll event is triggered it calls a C# method which is JSInvokable to store the current scroll position in a variable.

I want to be able to display this value on the page as it changes (mainly for development). But the JSInvokable method stores the value correctly but the two way binding is not updated.

The below is a pseudo example:

<div>Current Scroll Position: @scrollPosition.ToString()</div>


@code{

long scrollPosition = 0;

[JSInvokable("OnScroll")]
public void OnScroll(string index)
{
    int.TryParse(index, out var topIndex);
    scrollPosition = topIndex;
}
}

I was hoping that when the scrollPosition variable was updated from the JS calling the JSInvokable method, it would also update the DOM entry.

I realise I could do this all via JS but just wanted to try the binding as an example. I am not using any input fields for this but just a variable being displayed in the DOM and updated.

Am I doing this wrong?

Thank you

1
The property declaration does not need that @ at the start in the code block. I.E.: long ScrollPosition = 0; If that doesn't sort it, you can also try adding StateHasChanged(); after setting ScrollPosition = topIndex;Neil W
Thank you Neil, yes the @ at the start was a typo in this post, it wasn't in the code. But, adding the StateHasChanged() did indeed fix the problem (almost). It works as I scroll down the page, the DOM is changing and displaying the new scroll position, until, I navigate to another page and then come back to this page again. Then it stops updating the DOM even tho I can see the variable is being changing using Console.WriteLine ... any ideas? Thank you very much for your answer.Rowie
So, you're saying that if you navigate away, and then come back, you see console output from the method OnScroll (code in the component, not the javascript) where you are updating the variable scrollPosition? That's weird. Might be better to update your question with a fuller version of your actual code, instead of pseudo code, especially all of the component lifecycle events that you're overriding.Neil W

1 Answers

1
votes

Try to use:

InvokeAsync(() => { StateHasChanged(); });

Do it like this:

[JSInvokable("OnScroll")]
public async Task OnScroll(string index)
{
    int.TryParse(index, out var topIndex);
    scrollPosition = topIndex;
    await InvokeAsync(() => { StateHasChanged(); });
 
}