How can I improve this event handler class?

Hello,

to learn C++, I'm trying to write a simple game.

Here's my event handler class:

Header:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * File:   EventManager.h
 * Author: wernerkroneman
 *
 * Created on 29 augustus 2013, 12:01
 */

#ifndef EVENTMANAGER_H
#define	EVENTMANAGER_H

#include <SDL2/SDL.h>
#include <map>
#include <vector>

typedef SDL_Event Event;

class EventListener{
public:
    virtual void eventDidOccur(const Event& event)=0;
};

class EventManager {
public:
    EventManager();
    
    void registerListener(EventListener* listener,const SDL_EventType& type);
    
    void update();
    
    void eventDidOccur(const Event& event);
    
    bool handleEvent(const Event& event);
    
    virtual ~EventManager();
private:
    
    typedef std::map<SDL_EventType, std::vector<EventListener*> > ListenersMapType;
    
    ListenersMapType listeners;
    
    SDL_Joystick * joystick;
};

#endif	/* EVENTMANAGER_H */



Cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* 
 * File:   EventManager.cpp
 * Author: wernerkroneman
 * 
 * Created on 29 augustus 2013, 12:01
 */

#include "EventManager.h"
#include <iostream>

EventManager::EventManager() {
    
    //Check if there's any joysticks
    
    if( SDL_NumJoysticks() > 0 ) {
        
        joystick = SDL_JoystickOpen( 0 ); //If there's a problem opening the joystick
        //TODO error check if( stick == NULL ) {  }

    } //Open the joystick
    
}

void EventManager::update() {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        handleEvent(event);
    }
}

void EventManager::registerListener(EventListener* listener,const SDL_EventType& type){
    
    listeners[type].push_back(listener);
}

bool EventManager::handleEvent(const Event& event){
    ListenersMapType::iterator itr;
    if ((itr = listeners.find((SDL_EventType)(event.type))) != listeners.end()){
        for (std::vector<EventListener*>::iterator listenerItr = (*itr).second.begin(); listenerItr != (*itr).second.end(); listenerItr++)
            (*listenerItr)->eventDidOccur(event);
        
        return true;
    }
    return false;
}

EventManager::~EventManager() {
}



Basically, other objects can subclass "EventListener", implement "eventDidOccur" and then call "eventManager->registerListener(this, SDL_KEYDOWN)" to be notified whenever the specified type of event occurs.

It works just as intended, but could you please take a look at it, to see if any improvements could be made or if I'm making any mistakes?
Last edited on
Topic archived. No new replies allowed.