Stingray® Foundation : Chapter 6 Events Package : Chaining Event Routers
Chaining Event Routers
It is useful to route events through numerous objects in a system. In other words, an event may be routed through multiple objects before reaching its final destination. MFC has hard-coded routing logic to get messages to views and documents. The Events package takes advantage of the more flexible publish-subscribe pattern to accomplish message routing. Event routers can also be event listeners, and therefore they can listen to the events of other event routers. This flexible design means that the event routing logic in a system can be very dynamic and easy to configure.
The CComboRouterListener template class can be used to mix the IEventListener interface with an event router. The template parameter passed to CComboRouterListener is the base class, which must be a class derived from both IEventListener and IEventRouter. The CComboRouterListener class basically just implements the HandleEvent() method by forwarding it to the RouteEvent() method. Example 47 shows the implementation of CComboRouterListener.
Example 47 – Implementation of CComboRouterListener
template <class base_t>
class CComboRouterListener : public base_t
{
public:
virtual bool HandleEvent(IEvent* pIEvent)
{
bool bHandled = false;
 
if (pIEvent != NULL)
{
bHandled =
pIEvent->Dispatch(guid_cast<IEventRouter*>(this));
}
 
if (!bHandled)
bHandled = base_t::RouteEvent(pIEvent);
 
return bHandled;
}
};
The following code shows how you can use CComboRouterListener to create an object that is both an event router and an event listener. The CFoobarBase class inherits IEventRouterImpl and mixes in the IEventListener interface. CFoobarBase is an abstract base class because it does not implement the HandleEvent() method inherited from IEventListener. Wrapping CFoobarBase with the CComboRouterListener template class implements HandleEvent(). As a result, instances of CFoobar can be added as listeners to other event routers. They can also route events to listeners.
 
class CFoobarBase : public IEventRouterImpl, public IEventListener
{
};
 
typedef CComboRouterListener<CFoobarBase> CFoobar;