码迷,mamicode.com
首页 > 其他好文 > 详细

事件管理器

时间:2016-12-02 22:39:19      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:param   div   tty   避免   span   触发事件   code   blog   action   

项目开发过程中经常会用到代理事件,为方便管理,避免代码混乱,需要一个总的事件管理器:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class EventManager<T> {
    
    private static Dictionary<EventType,List<Action<T>>> eventDic = new Dictionary<EventType,List<Action<T>>>();

    /// <summary>
    /// 添加事件
    /// </summary>
    /// <param name="type"></param>
    /// <param name="act"></param>
    public static void AddEvent(EventType type, Action<T> act)
    {
        if (eventDic.ContainsKey(type))
        {
            if(!eventDic[type].Contains(act))
            {
                eventDic[type].Add(act);
            }
        }else
        {
            List<Action<T>> list = new List<Action<T>>();
            eventDic.Add(type, list);
            list.Add(act);
        }
    }

    /// <summary>
    /// 移除事件
    /// </summary>
    /// <param name="type"></param>
    public static void RemoveEvent(EventType type)
    {
        if (eventDic.ContainsKey(type))
        {
            eventDic.Remove(type);
        }
    }

    public static void RemoveEvent(EventType type, Action<T> act)
    {
        if (eventDic.ContainsKey(type))
        {
            if (eventDic[type].Contains(act))
            {
                eventDic[type].Remove(act);
            }
        }
    }

    /// <summary>
    /// 触发事件
    /// </summary>
    /// <param name="type"></param>
    /// <param name="data"></param>
    public static void TriggerEvent(EventType type , T data)
    {
        if (eventDic.ContainsKey(type))
        {
            List<Action<T>> list = eventDic[type];
            foreach (var callback in list)
            {
                callback(data);
            }
        }
    }
}

public enum EventType
{
    None = 0,
    Event1 = 1,
    Event2 = 2,
}

 

事件管理器

标签:param   div   tty   避免   span   触发事件   code   blog   action   

原文地址:http://www.cnblogs.com/zjw007/p/6127212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!