事件监听注册中心

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);
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值