Game Development Reference
In-Depth Information
private:
using EventHandlerList = std::vector<EventHandler*>;
using EventHandlerListIterator = EventHandlerList::iterator;
EventHandlerList m_listeners;
EventID m_id;
public:
explicit Event(EventID eventId);
void Send();
void SendToHandler(EventHandler& eventHandler);
void AttachListener(EventHandler& eventHandler);
void DetachListener(EventHandler& eventHandler);
EventID GetID() const { return m_id; }
};
The Event class has a vector of EventHandler pointers. These are pointers to objects that have
derived from EventHandler and are listening for a specific event. An Event also has an EventID
variable that allows the event to be identified.
The explicit keyword before the constructor ensures that instances of the class can only be created
when passing in an EventID or integer type. The class also has methods that are used to attach and
detach listeners and for sending the event either to all listeners of a specific EventHandler . Listing 21-6
shows the code for the AttachListener and DetachListener methods.
Listing 21-6. The AttachListener and DetachListener Methods
void Event::AttachListener(EventHandler& eventHandler)
{
m_listeners.push_back(&eventHandler);
}
void Event::DetachListener(EventHandler& eventHandler)
{
for (EventHandlerListIterator iter = m_listeners.begin();
iter != m_listeners.end();
++iter)
{
if (&eventHandler == *iter)
{
m_listeners.erase(iter);
break;
}
}
}
The AttachListener and DetachListener methods are responsible for adding and removing a given
EventHandler object from the m_listeners vector . This vector becomes useful when you would like
to send the Event to all of the pointers it stores, as you can see in Listing 21-7.
Search WWH ::




Custom Search