using System; using System.Collections.Generic; using Microsoft.JSInterop; namespace AntBlazor.JsInterop { public class DomEventService { private Dictionary> domEventListeners = new Dictionary>(); private readonly IJSRuntime _jsRuntime; public DomEventService(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public void AddEventListener(string dom, string eventName, Action callback) { if (!domEventListeners.ContainsKey($"{dom}-{eventName}")) { _jsRuntime.InvokeAsync(JSInteropConstants.addDomEventListener, dom, eventName, DotNetObjectReference.Create(new Invoker((p) => { callback?.Invoke(p); }))); } } } public class Invoker { private Action action; public Invoker(Action invoker) { this.action = invoker; } [JSInvokable] public void Invoke(T param) { action.Invoke(param); } } }