using System; using System.Collections.Generic; using System.Text.Json; using Microsoft.JSInterop; namespace AntDesign.JsInterop { public class DomEventService { private Dictionary> _domEventListeners = new Dictionary>(); private readonly IJSRuntime _jsRuntime; public DomEventService(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } private void AddEventListenerInternal(object dom, string eventName, Action callback) { if (!_domEventListeners.ContainsKey($"{dom}-{eventName}")) { _jsRuntime.InvokeAsync(JSInteropConstants.addDomEventListener, dom, eventName, DotNetObjectReference.Create(new Invoker((p) => { callback?.Invoke(p); }))); } } private void AddEventListenerToFirstChildInternal(object dom, string eventName, Action callback) { if (!_domEventListeners.ContainsKey($"{dom}-{eventName}")) { _jsRuntime.InvokeAsync(JSInteropConstants.addDomEventListenerToFirstChild, dom, eventName, DotNetObjectReference.Create(new Invoker((p) => { callback?.Invoke(p); }))); } } public void AddEventListener(object dom, string eventName, Action callback) { AddEventListenerInternal(dom, eventName, (e) => { JsonElement jsonElement = JsonDocument.Parse(e).RootElement; callback(jsonElement); }); } public void AddEventListener(object dom, string eventName, Action callback) { AddEventListenerInternal(dom, eventName, (e) => { T obj = JsonSerializer.Deserialize(e); callback(obj); }); } public void AddEventListenerToFirstChild(object dom, string eventName, Action callback) { AddEventListenerToFirstChildInternal(dom, eventName, (e) => { JsonElement jsonElement = JsonDocument.Parse(e).RootElement; callback(jsonElement); }); } public void AddEventListenerToFirstChild(object dom, string eventName, Action callback) { AddEventListenerToFirstChildInternal(dom, eventName, (e) => { T obj = JsonSerializer.Deserialize(e); callback(obj); }); } } public class Invoker { private Action _action; public Invoker(Action invoker) { this._action = invoker; } [JSInvokable] public void Invoke(T param) { _action.Invoke(param); } } }