ASP.NET MVC JQuery EventAggregator (Decoupled Event Handling)

The concept of Event Aggregation was first introduced to me as I read through the PRISM toolkit (Composite Application Guidance) from the Microsoft Patterns and Practises team.

It allows you to modularise your code and reduce dependencies between modules, I love it.
An example of how it benefits web applications would be:

Consider a simple 2 column web page layout where I have a div with content on the left (LeftBarRegion) and a div for the more content (MainContentRegion) on the right. Lets say that these two regions are defined in a Layout page (or Master Page) and the inner content of the MainContentRegion is changed by a JQuery ajax call. I have a LeftView and RightView which would fill the appropriate regions in my layout.

Now how do I get the view in the LeftBarRegion to talk to the view in the MainContentRegion and vice versa without knowing anything about the implementation details of each view? What if I also want to notify the parent layout page from either of the inner containers?

Welcome to the power of EventAggregator. We could have any content we like in either of the regions above and they can still talk to each other in a de-coupled fashion.

Enough talking lets watch it in action.

// Very simple - JQuery awesomeness
var EventAggregator = {

    // Ensure you are using the jquery data from the parent document so that everything goes
    // through the same EventAggregator.
    publish: function (event, args) {
        window.top.document.$(window.top.document).trigger(event, args);
    },

    subscribe: function (event, delegate) {
        window.top.document.$(window.top.document).bind(event, delegate)
    }
}

Now I can do this:

// In left content page
EventAggregator.publish(Events.SomeEventThatNeedsToBeHandled, { ID = 1 });

// In content page
EventAggregator.subscribe(Events.SomeEventThatNeedsToBeHandled, function (args) {  
    // Do stuff in the main content page when this event occurs
});

// In layout page
EventAggregator.subscribe(Events.SomeEventThatNeedsToBeHandled, function (args) {  
    // Do stuff in the layout page when this event occurs.
});
comments powered by Disqus