最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Blazor, how to constantly get currentWindow width? - Stack Overflow

programmeradmin8浏览0评论

I want to do something like this in a razor page:

@if (currentwidth<x)
{
   le code
}
else
{
    le other code
}

I have added javascript file and connected it to a utility service which works when I get the static width (which I tested).

js:

export function getCurrentWidth() {

    return window.addEventListener("resize", () => {
        window.innerWidth;
    });

}

UtilityService method:

public async Task<double> GetCurrentWidth() 
        {
            var m = await GetModule();
            var result = await m.InvokeAsync<double>("getCurrentWidth");
            return result;
        }

Razor file:

double width;

    protected async override Task OnInitializedAsync()
    {
        width = await utilityService.GetCurrentWidth();
    }

Thus the problem is I can't call it from OnInitailzedAsync since this function only fired once, so I need a function that constantly checks the GetCurrentWIdth() method to check for resize.

Is there another way of doing this in blazor or what method could I use/ Thank you in advance.

I want to do something like this in a razor page:

@if (currentwidth<x)
{
   le code
}
else
{
    le other code
}

I have added javascript file and connected it to a utility service which works when I get the static width (which I tested).

js:

export function getCurrentWidth() {

    return window.addEventListener("resize", () => {
        window.innerWidth;
    });

}

UtilityService method:

public async Task<double> GetCurrentWidth() 
        {
            var m = await GetModule();
            var result = await m.InvokeAsync<double>("getCurrentWidth");
            return result;
        }

Razor file:

double width;

    protected async override Task OnInitializedAsync()
    {
        width = await utilityService.GetCurrentWidth();
    }

Thus the problem is I can't call it from OnInitailzedAsync since this function only fired once, so I need a function that constantly checks the GetCurrentWIdth() method to check for resize.

Is there another way of doing this in blazor or what method could I use/ Thank you in advance.

Share Improve this question asked Aug 28, 2021 at 10:03 FrancoFranco 86213 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

First of all I'd like to point out that you may not have to solve your problem with javascript/C# code. If it's something in the html that you want to manipulate, you may just be better of using css. But I'll leave that up to you.

If however you truly need the window width like you mentioned above, then I would remend registering a listener to the window (as you've already done) and have that listener call a dotnet function. Doing this with static methods is quite easy, but for instance ponent this can be a bit trickier as you have to pass an object reference of the current object.

The [JsInvokable] indicates that this method can be called from javascript, which allows munication from the javascript event listener to dotnet.

CSharpFromJs.razor.cs

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Threading.Tasks;

public partial class CSharpFromJS
{
    private DotNetObjectReference<CSharpFromJS> _objectReference;
    public int WindowWidth { get; set; }


    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    protected override void OnInitialized()
    {
        _objectReference = DotNetObjectReference.Create(this);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await InitWindowWidthListener();
        }
    }

    [JSInvokable]
    public void UpdateWindowWidth(int windowWidth)
    {
        WindowWidth = windowWidth;
        StateHasChanged();
    }

    private async Task InitWindowWidthListener()
    {
        await JSRuntime.InvokeVoidAsync("AddWindowWidthListener", _objectReference);
    }

    public async ValueTask DisposeAsync()
    {
        await JSRuntime.InvokeVoidAsync("RemoveWindowWidthListener", _objectReference);
        _objectReference?.Dispose();
    }
}

CSharpFromJs.razor

@implements IAsyncDisposable

<h1>Window width: @WindowWidth</h1>

Javascript

// Manages the registered event listeners so they can be disposed later
let windowEventListeners = {};

function AddWindowWidthListener(objReference) {
    let eventListener = () => UpdateWindowWidth(objReference);
    window.addEventListener("resize", eventListener);
    windowEventListeners[objReference] = eventListener;
}

function RemoveWindowWidthListener(objReference) {
    window.removeEventListener("resize", windowEventListeners[objReference]);
}

function UpdateWindowWidth(objReference) {
    objReference.invokeMethodAsync("UpdateWindowWidth", window.innerWidth);
}

The only thing you should be careful with is when a ponent is disposd. You should remove the registered handlers in the DisposeAsync function to ensure that they're not still registered to prevent memory leaks.

This link might provide some better instructions on how to use this, but they don't explain the part about disposing handlers.

Note: This only works in 5 and later, as IAsyncDisposable was not yet implemented for ponent before that. If for some reason you're working with an earlier version, you could call it using IDisposable. But this could potentially cause deadlocks, so I would not remend it.

For me works the NuGet package BlazorPro.BlazorSize

Implement the method:

async void WindowResized(object _, BrowserWindowSize window){}

and all necessary Dependencies (see description).

发布评论

评论列表(0)

  1. 暂无评论