ant-design-blazor/components/core/JsInterop/DomEventService.cs

45 lines
1.1 KiB
C#
Raw Normal View History

2019-12-16 18:48:03 +08:00
using System;
using System.Collections.Generic;
using Microsoft.JSInterop;
namespace AntBlazor.JsInterop
{
public class DomEventService
{
private Dictionary<string, Func<object>> domEventListeners = new Dictionary<string, Func<object>>();
private readonly IJSRuntime _jsRuntime;
public DomEventService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
2020-03-11 16:40:07 +08:00
public void AddEventListener<T>(string dom, string eventName, Action<T> callback)
2019-12-16 18:48:03 +08:00
{
2020-03-11 16:40:07 +08:00
if (!domEventListeners.ContainsKey($"{dom}-{eventName}"))
2019-12-16 18:48:03 +08:00
{
2020-03-11 16:40:07 +08:00
_jsRuntime.InvokeAsync<string>(JSInteropConstants.addDomEventListener, dom, eventName, DotNetObjectReference.Create(new Invoker<T>((p) =>
2019-12-16 18:48:03 +08:00
{
2020-03-11 16:40:07 +08:00
callback?.Invoke(p);
2019-12-16 18:48:03 +08:00
})));
}
}
}
2020-03-11 16:40:07 +08:00
public class Invoker<T>
2019-12-16 18:48:03 +08:00
{
2020-03-11 16:40:07 +08:00
private Action<T> action;
2019-12-16 18:48:03 +08:00
2020-03-11 16:40:07 +08:00
public Invoker(Action<T> invoker)
2019-12-16 18:48:03 +08:00
{
this.action = invoker;
}
[JSInvokable]
2020-03-11 16:40:07 +08:00
public void Invoke(T param)
2019-12-16 18:48:03 +08:00
{
2020-03-11 16:40:07 +08:00
action.Invoke(param);
2019-12-16 18:48:03 +08:00
}
}
}