You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.8 KiB
C#
61 lines
1.8 KiB
C#
using System.Collections.Generic;
|
|
|
|
namespace Script.FrameWork.EventSystem
|
|
{
|
|
public delegate void Dispatcher(EventArgs eventArgs);
|
|
|
|
public class EventDispatcher
|
|
{
|
|
private Dictionary<int, Dictionary<object, Dispatcher>> _dispatcherDic = new();
|
|
|
|
public void AddEventListener(int eventKey, object obj, Dispatcher handler)
|
|
{
|
|
if (!_dispatcherDic.TryGetValue(eventKey, out var dic))
|
|
{
|
|
dic = new Dictionary<object, Dispatcher>();
|
|
_dispatcherDic.Add(eventKey, dic);
|
|
}
|
|
if (!dic.TryGetValue(obj, out var dispatcher))
|
|
{
|
|
dic.Add(obj, handler);
|
|
return;
|
|
}
|
|
dic[obj] += handler;
|
|
}
|
|
|
|
public void AddUniqueEventListener(int eventKey, object obj, Dispatcher handler)
|
|
{
|
|
if (!_dispatcherDic.TryGetValue(eventKey, out var dic))
|
|
{
|
|
dic = new Dictionary<object, Dispatcher>();
|
|
_dispatcherDic.Add(eventKey, dic);
|
|
}
|
|
if (!dic.TryGetValue(obj, out var dispatcher))
|
|
{
|
|
dic.Add(obj, handler);
|
|
return;
|
|
}
|
|
dic[obj] = handler;
|
|
}
|
|
|
|
public void RemoveEventListener(int eventKey, object obj)
|
|
{
|
|
if (_dispatcherDic.TryGetValue(eventKey, out var dic))
|
|
{
|
|
if (dic.ContainsKey(obj))
|
|
dic.Remove(obj);
|
|
}
|
|
}
|
|
|
|
public void TriggerEventListener(int eventKey, EventArgs eventArgs)
|
|
{
|
|
if (_dispatcherDic.TryGetValue(eventKey, out var dic))
|
|
{
|
|
foreach (var (_, handler) in dic)
|
|
{
|
|
handler.Invoke(eventArgs);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |