using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using DG.Tweening;
using EnumDefine;
using System;
public class BattleEventCenter
{
private static BattleEventCenter mInstance;
public static BattleEventCenter Instance
{
get
{
if (mInstance == null)
{
mInstance = new BattleEventCenter ();
}
return mInstance;
}
}
public delegate void OnNotification(IMessage msg);
private static Dictionary<EventKey,OnNotification> eventListeners = new Dictionary<EventKey, OnNotification>();
public static List<Delegate> delegateList;
/// <summary>
/// 注册某一事件的监听函数
/// </summary>
/// <param name="eventKey">Event key.</param>
/// <param name="notif">Notif.</param>
public static bool AddEventListener(EventKey eventKey,OnNotification notif)
{
if (notif == null || eventKey == null) {
Debug.LogError ("注册监听时,参数不全!!!");
return false;
}
if (!eventListeners.ContainsKey (eventKey)) {
eventListeners.Add (eventKey, notif);
return true;
}
else
{
delegateList = new List<Delegate>( eventListeners[eventKey].GetInvocationList() );
if (delegateList.Contains (notif))
{
Debug.LogError ("某一主体内的函数,重复订阅相同的事件:" +eventKey.ToString());
return false;
}
else
{
eventListeners [eventKey] += notif;
return true;
}
//delegateList = null;
}
}
/// <summary>
/// 分发事件
/// </summary>
/// <param name="eventKey">事件 key.</param>
/// <param name="msg">通知的消息.</param>
public static void DispatchEvent(EventKey eventKey,IMessage msg)
{
if (!eventListeners.ContainsKey (eventKey))
{
//Debug.LogError ("无人监听此事件: " + eventKey.ToString());
return;
}
else
{
//Debug.LogError ("成功分发事件:"+eventKey.ToString());
eventListeners [eventKey] (msg);
}
}
/// <summary>
/// 直接移除某一事件的全部监听,慎用!
/// </summary>
/// <param name="eventKey">Event key.</param>
public static void RemoveEventListener(EventKey eventKey)
{
if (!eventListeners.ContainsKey (eventKey))
return;
eventListeners [eventKey] = null;
eventListeners.Remove (eventKey);
}
/// <summary>
/// 移除某一事件的特定监听函数
/// </summary>
/// <param name="eventKey">Event key.</param>
/// <param name="notif">要移除的监听函数</param>
public static void RemoveEventListener(EventKey eventKey,OnNotification notif)
{
//Debug.LogError ("remove " + eventKey.ToString());
if (!eventListeners.ContainsKey (eventKey))
{
Debug.LogError ("企图移除的监听事件不存在!");
return;
}
eventListeners [eventKey] -= notif;
if (eventListeners [eventKey] == null)
{
RemoveEventListener (eventKey);
}
}
}
事件监听注册中心
最新推荐文章于 2022-12-17 14:00:00 发布