Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ observer pattern for event handling.
#include "EventDispatcher.h"
void EventDispatcher::addListener( Listener *l )
{
mListeners.push_back(l);
}
void EventDispatcher::removeListener( Listener *l )
{
mListeners.erase( std::remove( mListeners.begin(), mListeners.end(), l ), mListeners.end() );
//having toruble with the rmove function...
}
void EventDispatcher::dispatchEvent()
{
for( std::vector<Listener*>::iterator listener = mListeners.begin(); listener != mListeners.end(); ++listener )
{
(*listener)->handleEvent();
}
}
#include "Listener.h"
#include <stdio.h>
#include <vector>
#include <algorithm>
class EventDispatcher {
public:
void addListener( Listener* );
void removeListener( Listener* );
protected:
std::vector<Listener*> mListeners;
virtual void dispatchEvent();
};
typedef std::vector<Button>::iterator ButtonIter;
MenuState::MenuState(): mButtonListener(this)
{
for( int i = 0; i != 10; i++ )
{
mPreferences.push_back( Button(i) );
}
//add listeners
for( ButtonIter b = mPreferences.begin(); b != mPreferences.end(); b++ )
{
b->addListener( &mButtonListener );
}
}
#include "EventDispatcher.h"
class MenuState : public AppState
{
public:
MenuState();
private:
std::vector<Button> mButtons;
// Event Listeners
// Buttons
class ButtonListener : public Listener
{
PrefListState* parent;
public:
ButtonListener( PrefListState* p ){ parent = p; }
void handleEvent( int ID )
{
std::cout << "Button Pressed: " << ID << std::endl;
}
} mButtonListener;
};
class Listener
{
public:
virtual void handleEvent(){}
virtual void handleEvent( int ID ){}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.