EventEmitter.h
1 //-*-C++-*-
2 /***************************************************************************
3  *
4  * Copyright (C) 2019 by Dean Shaff, Andrew Jameson and Willem van Straten
5  * Licensed under the Academic Free License version 2.1
6  *
7  ***************************************************************************/
8 
9 #ifndef __EventEmitter_h
10 #define __EventEmitter_h
11 
12 #include <string>
13 #include <vector>
14 #include <map>
15 #include <iostream>
16 
31 template<typename FuncType>
32 class EventEmitter {
33 
34 public:
35 
36  EventEmitter ();
37 
38  void on (const std::string& event_name, FuncType func);
39 
40  void on (const std::string& event_name, FuncType* func);
41 
42  template<class ... Types>
43  void emit (const std::string& event_name, Types ... args);
44 
45 private:
46 
47  std::map<std::string, std::vector<FuncType*> > event_map;
48 
49 };
50 
51 
52 template<typename FuncType>
54 { }
55 
56 template<typename FuncType>
57 void EventEmitter<FuncType>::on(const std::string& event_name, FuncType _func)
58 {
59  on(event_name, &_func);
60 }
61 
62 template<typename FuncType>
63 void EventEmitter<FuncType>::on(const std::string& event_name, FuncType* _func)
64 {
65  if (event_map.find(event_name) == event_map.end()) {
66  event_map[event_name] = {_func};
67  } else {
68  event_map[event_name].push_back(_func);
69  }
70 }
71 
72 template<typename FuncType>
73 template<class ... Types>
74 void EventEmitter<FuncType>::emit (const std::string& event_name, Types ... args)
75 {
76  if (event_map.find(event_name) != event_map.end())
77  {
78  auto func_b = event_map[event_name].begin();
79  auto func_e = event_map[event_name].end();
80  for (; func_b != func_e; func_b++) {
81  (**func_b)(args...);
82  }
83  }
84 }
85 
86 #endif
Implements a simple event emitter class.
Definition: EventEmitter.h:32

Generated using doxygen 1.8.17