using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using Newtonsoft.Json.Linq;
///
/// 2020.11.30 启用事件分发器
///
public class EventDispatcher : MonoSingleton
{
static Dictionary> _EventListeners
= new Dictionary>();
///
/// 注册时间监听
///
///
///
public void AddEventListener(string type, Action ac)
{
if (!_EventListeners.ContainsKey(type))
{
_EventListeners.Add(type, new List());
}
_EventListeners[type].Add(ac);
}
///
/// 设置事件监听
/// 注意:当次设定值会覆盖之前所有的注册事件而成为唯一事件
///
///
///
public void SetEventListener(string type, Action listener)
{
if (!_EventListeners.ContainsKey(type))
{
_EventListeners.Add(type, new List());
}
else
{
_EventListeners[type].Clear();
}
_EventListeners[type].Add(listener);
}
///
/// 移除事件监听
///
///
///
public void RemoveEventListener(string type, Action listener)
{
if (_EventListeners.ContainsKey(type))
{
_EventListeners[type].Remove(listener);
if (_EventListeners[type].Count <= 0)
{
_EventListeners.Remove(type);
}
}
}
///
/// 清除特定类型事件监听
///
///
public void RemoveAllEventListener(string type)
{
if (_EventListeners.ContainsKey(type))
{
_EventListeners.Remove(type);
}
}
///
/// 清除全部事件监听
///
public void ClearAllEventListeners()
{
foreach (string type in _EventListeners.Keys)
{
_EventListeners[type].Clear();
}
_EventListeners.Clear();
}
///
/// 发送事件
///
///
///
public void DispatchEvent(string type, object _params1 = null, object _params2 = null)
{
if (_EventListeners.ContainsKey(type))
{
foreach (Action ac in _EventListeners[type])
{
if (ac != null)
{
ac();
}
}
}
}
}