From 52af9730148c0f3e653f8e0d4b70d269a31aeed1 Mon Sep 17 00:00:00 2001 From: Michael Fabian 'Xaymar' Dirks Date: Wed, 23 Jan 2019 20:00:35 +0100 Subject: [PATCH] util-event: Listen, Silence callbacks and other operators --- source/util-event.hpp | 71 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 59 insertions(+), 12 deletions(-) diff --git a/source/util-event.hpp b/source/util-event.hpp index c00ed5c0..e3c85183 100644 --- a/source/util-event.hpp +++ b/source/util-event.hpp @@ -26,40 +26,87 @@ namespace util { class event { std::list> listeners; - public: - void add(std::function listener) + std::function listen_cb; + std::function silence_cb; + + public /* functions */: + // Add new listener. + inline void add(std::function listener) { + if (listeners.size() == 0) { + if (listen_cb) { + listen_cb(); + } + } listeners.push_back(listener); } - void remove(std::function listener) + // Remove existing listener. + inline void remove(std::function listener) { listeners.remove(listener); + if (listeners.size() == 0) { + if (silence_cb) { + silence_cb(); + } + } } - // Not valid without the extra template. + // Check if empty / no listeners. + inline bool empty() + { + return listeners.empty(); + } + + // Remove all listeners. + inline void clear() + { + listeners.clear(); + if (silence_cb) { + silence_cb(); + } + } + + public /* operators */: + // Call Listeners with arguments. + /// Not valid without the extra template. template - void operator()(_args... args) + inline void operator()(_args... args) { for (auto& l : listeners) { l(args...); } } - operator bool() + // Convert to bool (true if not empty, false if empty). + inline operator bool() { - return !listeners.empty(); + return !this->empty(); } - public: - bool empty() + // Add new listener. + inline event<_args...>& operator+=(std::function listener) { - return listeners.empty(); + this->add(listener); + return *this; } - void clear() + // Remove existing listener. + inline event<_args...>& operator-=(std::function listener) { - listeners.clear(); + this->remove(listener); + return *this; + } + + public /* events */: + void set_listen_callback(std::function cb) + { + this->listen_cb = cb; + } + + void set_silence_callback(std::function cb) + { + this->silence_cb = cb; } }; } // namespace util