Skip to content

Commit

Permalink
add listeners() impl
Browse files Browse the repository at this point in the history
  • Loading branch information
heapwolf committed Aug 12, 2015
1 parent d6baab4 commit c8013e9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 9 additions & 3 deletions events.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,16 @@ class EventEmitter {
return static_cast<typename traits<Callback>::fn>(cb);
}

int listeners = 0;
int _listeners = 0;

public:

int maxListeners = 10;

int listeners() {
return this->_listeners;
}

template <typename Callback>
void on(std::string name, Callback cb) {

Expand All @@ -43,10 +47,10 @@ class EventEmitter {
throw new std::runtime_error("duplicate listener");
}

if (++this->listeners >= this->maxListeners) {
if (++this->_listeners >= this->maxListeners) {
std::cout
<< "warning: possible EventEmitter memory leak detected. "
<< this->listeners
<< this->_listeners
<< " listeners added. "
<< std::endl;
};
Expand All @@ -64,6 +68,7 @@ class EventEmitter {

void off() {
events.clear();
this->_listeners = 0;
}

void off(std::string name) {
Expand All @@ -72,6 +77,7 @@ class EventEmitter {

if (it != events.end()) {
events.erase(it);
this->_listeners--;

auto once = events_once.find(name);
if (once != events_once.end()) {
Expand Down
2 changes: 2 additions & 0 deletions test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ int main (int argc, char* argv[]) {
count3++;
ASSERT("events were fired even though all listeners were removed", false);
});

ASSERT("the correct number of listeners has been reported", ee.listeners() == 4);

ee.off();

Expand Down

0 comments on commit c8013e9

Please sign in to comment.