Chapter 19. Event factories

An event factory is a generic thread-safe object for dispatching internal application events. Application events are identified by an event key, and have some associated event data.

typedef eventfactory<std::string, int> myfactory_t;

myfactory_t myfactory(myfactory_t::create());

This example creates an event factory whose events are identified by a std::string, with each event's data being a simple int.

Handlers for an event are implemented by subclassing from x::eventhandlerObj. This is a template class, whose template parameter is the event data type.

class myEventHandlerObj : public x::eventhandlerObj<int> {

public:
    myEventHandlerObj() noexcept {}
    ~myEventHandlerObj() {}
    void event(const int &eventArg);
};

typedef x::ref<myEventHandlerObj> myEventHandler;

myEventHandler evh(myEventHandler::create());

x::eventhandlerObj is a reference-counted object. The event handler subclass must implement the event method, that takes a constant reference to the event data type as its sole argument.

The event handler gets registered with the event factory by invoking the registerHandler method:

x::eventregistration regevent(myfactory->registerHandler("fileavailable",
                                                         evh);

The event handler is associated with an event key fileavailable. This example uses an event factory whose events are keyed by a std::string. Reported events with the given event key are passed along to all event handlers registered for the event key, and each registered handler's event() method receives the event argument, the int.

registerHandler() returns an x::eventregistration. This is an opaque reference to the registered event handler. The registered event handler receives events as long as this opaque reference remains in scope. When this x::eventregistration goes out of scope, the event handler gets deregistered from the event factory, and will no longer receive any reported events.

An event gets reported by invoking event():

myfactory->event("fileavailable", 4);

All event handlers that are registered for the fileavailable event are invoked, receiving 4 as the event handler's argument. x::eventfactory has several overloaded event() methods for reporting multiple events in several convenient ways.