Reputation: 83
I don't want to implement my logic in OnInitializedAsync, which happens on initial load. This should happen after the initial load and when user start resizing the browser window.
Thanks.
Upvotes: 7
Views: 9256
Reputation: 171
It can be more simple
Add the following script directly into your index.html or within the App.razor file in the body section:
<script>
window.registerViewportChangeCallback = (dotnetHelper) => {
window.addEventListener('load', () => {
dotnetHelper.invokeMethodAsync('OnResize', window.innerWidth, window.innerHeight);
});
window.addEventListener('resize', () => {
dotnetHelper.invokeMethodAsync('OnResize', window.innerWidth, window.innerHeight);
});
}
</script>
Now, utilize the OnResize method in your Blazor component:
public int ViewportWidth { get; set; }
public int ViewportHeight { get; set; }
[JSInvokable]
public void OnResize(int width, int height)
{
if(ViewportWidth == width && ViewportHeight == height) return;
ViewportWidth = width;
ViewportHeight = height;
StateHasChanged();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("window.registerViewportChangeCallback", DotNetObjectReference.Create(this));
}
}
Upvotes: 4
Reputation: 4246
The answer is that you catch the event in Javascript, and then call a Blazor method through JS Interop.
However, I strongly recommend you NOT handle events that could fire very frequently, like mouse position changes or window size changes, with constant calls back to Blazor. Handle those using pure Javascript, and call a Blazor method after some sensible completion-- the mouse button has been released, or a certain delay time has passed, etc.
This is especially true in server flavor, and with insidious consequences. You could have a site that works fine in development, but fails horribly when deployed, do to the higher latency of a distant server.
Upvotes: 11