can you please explain a bit more detail?
So, you have an "event", which is just an id to distinguish between events. It can be an enum, #DEFINE'd ints, hashed strings, whatever.
You also have a "delegate", which is the code that should be executed when the event happens. Delegates in C++ (which is what I assume you're using) are a pretty big topic, so I'll link you to the stackoverflow question
What is a C++ delegate?Lets say you have a class that keeps track of the player's score, and whenever an enemy is killed, the score should increase by the enemy's point value.
Pseudocode would look like this:
class ScoreTracker
{
class EnemyKilledDelegate : Delegate
{
int totalPoints;
virtual void operator()(void* data)
{
totalPoints = (int*)data;
}
}
ScoreTracker()
{
//...
EventManager* mgr;
EnemyKilledDelegate* del;
mgr.RegisterListener("EnemyKilled", del);
//...
}
}
The event manager would then keep some sort of dictionary to call the delegates when the event occurs:
class EventManager
{
map<string, vector<Delegate*>*> eventMap; // map strings to (pointers to (vector of pointers to delegates))
RegisterListener(string event, Delegate* delegate)
{
// get the vector of delegates for the event (or create a new one)
vector<Delegate>* eventListeners = eventMap.getOrCreate(event);
eventListeners.add(delegate); // add the delegate
}
ProcessEvent(string event, void* data)
{
// get the vector of delegates for the event (or create a new one)
vector<Delegate>* eventListeners = eventMap.getOrCreate(event);
foreach(Delegate* del in eventListeners) // loop through and call each delegate
{
(*del)(data);
}
}
}
And finally, to fire an event:
class Enemy
{
int pointValue;
Die()
{
//...
EventManager* mgr;
mgr.ProcessEvent("EnemyKilled", &pointValue);
//...
}
}
Edited by turch, 14 February 2013 - 10:39 AM.