-
Notifications
You must be signed in to change notification settings - Fork 2
/
event.cpp
39 lines (34 loc) · 888 Bytes
/
event.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
// Nonolith Connect
// https://github.com/nonolith/connect
// Publish/subscribe events helper
// Released under the terms of the GNU GPLv3+
// (C) 2012 Nonolith Labs, LLC
// Authors:
// Kevin Mehall <[email protected]>
#include "dataserver.hpp"
#include <boost/foreach.hpp>
void EventListener::subscribe(Event& e, void_function h){
unsubscribe();
event = &e;
handler = h;
event->listeners.insert(this);
}
void EventListener::unsubscribe(){
if (event){
event->listeners.erase(this);
event = 0;
}
}
void Event::notify(){
for (std::set<EventListener*>::iterator it=listeners.begin(); it!=listeners.end();){
EventListener* e = *it;
it++; // Increment before calling handler in case the handler removes this listener,
// which would invalidate the iterator.
e->handler();
}
}
Event::~Event(){
BOOST_FOREACH(EventListener* e, listeners){
e->event = 0;
}
}