using System.Collections; using System.Collections.Generic; using UnityEngine; namespace WK { /// /// 作用域范围的消息通知 /// public class ScopedNotification { public delegate void NotificatonHandler(params object[] args); private Dictionary> m_EventListeners = new Dictionary>(); public void AddObserver(string eventName, NotificatonHandler handler) { if (handler == null) { return; } if (string.IsNullOrEmpty(eventName)) { return; } List handlers; if (!m_EventListeners.ContainsKey(eventName)) { m_EventListeners.Add(eventName, new List()); } handlers = m_EventListeners[eventName]; handlers.Add(handler); } public void RemoveObserver(string eventName, NotificatonHandler handler) { if(handler == null) { return; } if(string.IsNullOrEmpty(eventName)) { return; } if (!m_EventListeners.ContainsKey(eventName)) return; List handlers = m_EventListeners[eventName]; if(handlers.Contains(handler)) handlers.Remove(handler); } public void RemoveEvent(string eventName) { if (string.IsNullOrEmpty(eventName)) { return; } if(m_EventListeners.ContainsKey(eventName)) { m_EventListeners.Remove(eventName); } } public void Clean() { m_EventListeners.Clear(); } public void PostNotification(string eventName, params object[] args) { if (string.IsNullOrEmpty(eventName)) { return; } if (!m_EventListeners.ContainsKey(eventName)) return; List handlers = m_EventListeners[eventName]; for(int i = 0; i < handlers.Count; i++) { var handler = handlers[i]; if(handler != null) { handler(args); } } } public void PostNotification(string eventName) { PostNotification(eventName, null); } } }