LostBeard / SpawnDev.BlazorJS

Full Blazor WebAssembly and Javascript Interop with multithreading via WebWorkers
https://blazorjs.spawndev.com
MIT License
78 stars 6 forks source link

How to subscribe to window.matchMedia changes #10

Closed RonPeters closed 10 months ago

RonPeters commented 10 months ago

First of all, thank you for creating this project. I have gotten immediate use out of it.

I am trying to match this equivalent JavaScript using your API and can't figure it out. This code watches for changes in the color scheme and then calls my instance method "SystemThemeChanged": window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({ matches }) => { dotNetHelper.invokeMethodAsync("SystemThemeChanged"); });

The event listener is not being added to the window, but rather to the MediaQueryList returned from matchMedia. How do I accomplish this?

LostBeard commented 10 months ago

There is still a lot of JSObject work that I need to complete. I am basically filling in the object properties and methods as I need them or as needed by others. Thank you for letting me know what you needed.

I have updated MediaQueryList and MediaQueryListEvent to accommodate. The repo has been updated. I will update the Nuget shortly.

Example usage in a component

[Inject]
BlazorJSRuntime JS { get; set; }

MediaQueryList? mediaQueryList = null;

void Handler(MediaQueryListEvent mediaQueryListEvent)
{
    // handle event
}

void AttachHandler()
{
    using var window = JS.Get<Window>("window");
    mediaQueryList = window.MatchMedia("(prefers-color-scheme: dark)");
    mediaQueryList.OnChange += Handler;
}

void DetachHandler()
{
    mediaQueryList.OnChange -= Handler;
}
RonPeters commented 10 months ago

Perfect. Your responsiveness is much appreciated! Just bought you a coffee

LostBeard commented 10 months ago

Awesome. I got it. Thank you! Glad I could help.