SharpLibEar/Manager.cs
author StephaneLenclud
Tue, 16 Aug 2016 12:25:20 +0200
changeset 234 0c75dec19d39
child 235 ba14a29944c4
permissions -rw-r--r--
Ear cleanup.
     1 //
     2 using System;
     3 using System.Collections.Generic;
     4 using System.ComponentModel;
     5 using System.Linq;
     6 using System.Reflection;
     7 using System.Runtime.Serialization;
     8 using SharpLib.Utils;
     9 
    10 namespace SharpLib.Ear
    11 {
    12     /// <summary>
    13     /// Event Action Router (Ear) is a generic and extensible framework allowing users to execute actions in response to events. 
    14     /// Users can implement their own events and actions.
    15     /// </summary>
    16     [TypeConverter(typeof(TypeConverterJson<Manager>))]
    17     [DataContract]
    18     public class Manager
    19     {
    20         /// <summary>
    21         /// Access the currently installed EAR manager. 
    22         /// </summary>
    23         public static Manager Current = null;
    24 
    25         /// <summary>
    26         /// Our events instances.
    27         /// </summary>
    28         [DataMember]
    29         public List<Event> Events;
    30 
    31         /// <summary>
    32         /// Constructor
    33         /// </summary>
    34         public Manager()
    35         {
    36             Init();
    37         }
    38 
    39         /// <summary>
    40         /// Executes after internalization took place.
    41         /// </summary>
    42         public void Init()
    43         {
    44             if (Events == null)
    45             {
    46                 Events = new List<Event>();
    47             }
    48             
    49         }
    50 
    51         /// <summary>
    52         /// Trigger the given event.
    53         /// </summary>
    54         /// <param name="aEventType"></param>
    55         public void TriggerEvent<T>() where T: class
    56         {
    57             //Only trigger enabled events matching the desired type
    58             foreach (Event e in Events.Where(e => e.GetType() == typeof(T) && e.Enabled))
    59             {
    60                 e.Trigger();
    61             }
    62         }
    63 
    64 
    65         /// <summary>
    66         /// Remove the specified action from the event it belongs too.
    67         /// </summary>
    68         /// <param name="aAction"></param>
    69         public void RemoveAction(Action aAction)
    70         {
    71             foreach (Event e in Events)
    72             {
    73                 if (e.Actions.Remove(aAction))
    74                 {
    75                     //We removed our action, we are done here.
    76                     return;
    77                 }
    78             }
    79         }
    80     }
    81 }