Handling Event Notification - An Alternative Approach

I remember reading about an approach to create an Object-Oriented API for an application, similar to Visual Studio, using documents, tool windows, menu items, and other objects.  The approach was to create events for each transaction and have these events bubble up to the parent.  However, to me this seemed like a lot of work.  However, I thought of an alternative approach that reduced that amount, though some care is needed with it.

Essentially, the object is an internal static object, that has a static event (EventTriggered) and a static method to trigger it (FireEvent).  The method takes the name of an event, the object raising the event, and the targeted object (which may be an inner object, like a child of a collection).  So the class could look like this:

internal static class Notifier
{
    public static event NotifiedEventHandler EventTriggered;

    public static void FireEvent(string eventName, object sourceObject, object targetObject)
    {
         //Fires the event
    }
}

All objects that want to raise some notification work directly with this object by calling Notifier.FireEvent, as such:

Notifier.FireEvent("Doc Added", this, docObject);

However, there are some caveats to understand

  • This object should be confined to a single set of objects, because string keys for event names takes great care to manage.
  • Or, some scheme needs to be used to manage this, like adding in a type name as another parameter.
  • In addition, the objects fired must be known (have some idea of what they are) to convert them.

In the case of the API I mentioned before, which I have worked on, I found this to be a better approach.

Comments

No Comments