sculpto
event_dispatcher.h
Go to the documentation of this file.
1/*!****************************************************************//*!*
2 * \file event_dispatcher.h
3 * \brief Event dispatcher class implementation module.
4 *
5 * \author Sabitov Kirill
6 * \date 25 June 2022
7 *********************************************************************/
8
9#pragma once
10
11#include "event.h"
13
14namespace scl
15{
20 {
21 template <typename Tevent>
22 using event_callback = std::function<bool(Tevent &)>;
23 using base_event_callback = std::function<bool(event &)>;
24 using callback_list = std::vector<base_event_callback>;
25
26 private:
27 static std::map<string_id, callback_list> EventHandlers;
28
29 public:
30 /*!*
31 * Add event listner to specific event function.
32 *
33 * \tparam Tevent - event to set listner to.
34 * \param Event - callback to be called on event dispatch.
35 * \return None.
36 */
37 template <typename Tevent>
38 static void AddEventListner(base_event_callback &&EventCallback)
39 {
40 auto event_handlers = EventHandlers.find(Tevent::StaticType);
41 if (event_handlers == EventHandlers.end())
42 EventHandlers.emplace(Tevent::StaticType, std::vector { std::move(EventCallback) });
43 else
44 event_handlers->second.push_back(std::move(EventCallback));
45 }
46
47 /*!*
48 * Add event listner to specific event function.
49 *
50 * \tparam Tevent - event to set listner to.
51 * \param Event - callback to be called on event dispatch.
52 * \return None.
53 */
54 template <typename Tevent>
55 static void AddEventListner(std::function<bool(Tevent &)> &&EventCallback)
56 {
57 AddEventListner<Tevent>([callback = std::move(EventCallback)](event &Event)
58 {
59 if (Event.GetType() != Tevent::StaticType) return false;
60 return callback(static_cast<Tevent &>(Event));
61 });
62 }
63
64 /*!*
65 * Dispatch specific event function.
66 * Calls all callbacks, listing to that event.
67 *
68 * \param Event - event to handle.
69 * \return None.
70 */
71 template <typename Tevent>
72 static void Invoke(Tevent &Event)
73 {
74 std::map<string_id, callback_list>::iterator event_handlers = EventHandlers.find(Event.GetType());
75 if (event_handlers == EventHandlers.end()) return;
76
77 for (const auto &callback : event_handlers->second)
78 {
79 Event.Handled |= callback(Event);
80 if (Event.Handled) break;
81 }
82 }
83 };
84}
static void AddEventListner(std::function< bool(Tevent &)> &&EventCallback)
static void AddEventListner(base_event_callback &&EventCallback)
static void Invoke(Tevent &Event)
virtual u32 GetType() const =0
Definition: base.h:33
String id generating by CRC32 algoritm implemetation module. Can be used both in compiletime anr runt...