Mike Nichols - Son of Nun Technology

Divine Event Handling

There is a better way of doing this I am sure, but I needed to make sure that handlers that were assigned to a control's events were kept in reverse order.

For example, I have a control on the page that has an event that is being 'listened' to by the page for navigation instructions. A number of child controls are on the page and will also need to be listening to this event as well. Now, the other controls are dynamically loaded and will be attaching their event handlers as they are done so...but that means that their handlers will not be fired until AFTER the page handler is fired.

So basically, I needed to create a way to enforce that the first handler attached will always be the last one in the invocation list order. so i drummed up a little utility to do exactly this...The first method name I came up with was RegisterEvent_FirstRegisteredAlwaysLast, but that made me think of...

But many that are first shall be last; and the last shall be first. For the kingdom of heaven is like unto a man that is an householder, which went out early in the morning to hire labourers into his vineyard.
(Mat 19:30-20:1)

So I couldn't resist a better method name...

 

    public class EventUtil

    {

        /// <summary>

        /// Keeps the first event registered LAST on invocation order and the most recent event added is FIRST.

        /// </summary>

        /// <typeparam name="TEventArgs"></typeparam>

        /// <param name="eventObj"></param>

        /// <param name="eventHandlerToRegister"></param>

        /// <returns></returns>

        public static EventHandler<TEventArgs> RegisterEvent_KingdomOfHeaven<TEventArgs>(EventHandler<TEventArgs> eventObj, Proc<object, TEventArgs> eventHandlerToRegister)

                where TEventArgs : System.EventArgs

        {

            if (eventObj == null)

            {

                eventObj += new EventHandler<TEventArgs>(eventHandlerToRegister);

                return eventObj;

            }

 

            Delegate[] handlers = eventObj.GetInvocationList();

            eventObj = null;

            eventObj += new EventHandler<TEventArgs>(eventHandlerToRegister);

 

            foreach (Delegate handler in handlers)

            {

                eventObj += new EventHandler<TEventArgs>((EventHandler<TEventArgs>)handler);

            }

 

            return eventObj;

        }

    }

Now I can just stick this in my control

:

 public void RegisterEvent(Proc<object, EventArgs<int>> eventHandler)

            {

                Event1 =EventUtil.RegisterEvent_KingdomOfHeaven<EventArgs<int>>(Event1,eventHandler);

 

            }