From 956a401f9c955f26b7e661dc80f76bfc43fc4124 Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 1 Sep 2018 23:28:28 +0800 Subject: Initial commit --- CruUI/cru_event.h | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 CruUI/cru_event.h (limited to 'CruUI/cru_event.h') diff --git a/CruUI/cru_event.h b/CruUI/cru_event.h new file mode 100644 index 00000000..f5e548c0 --- /dev/null +++ b/CruUI/cru_event.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include +#include +#include + +#include "base.h" + +namespace cru { + //Base class of all event args. + class BasicEventArgs : public Object + { + public: + explicit BasicEventArgs(Object* sender) + : sender_(sender) + { + + } + BasicEventArgs(const BasicEventArgs& other) = default; + BasicEventArgs(BasicEventArgs&& other) = default; + BasicEventArgs& operator=(const BasicEventArgs& other) = default; + BasicEventArgs& operator=(BasicEventArgs&& other) = default; + ~BasicEventArgs() override = default; + + //Get the sender of the event. + Object* GetSender() const + { + return sender_; + } + + private: + Object* sender_; + }; + + + //A non-copyable non-movable Event class. + //It stores a list of event handlers. + //TArgsType must be subclass of BasicEventArgs. + template + class Event + { + public: + static_assert(std::is_base_of_v, + "TArgsType must be subclass of BasicEventArgs."); + + + using ArgsType = TArgsType; + using EventHandler = Action; + using EventHandlerPtr = std::shared_ptr; + + Event() = default; + Event(const Event&) = delete; + Event& operator = (const Event&) = delete; + Event(Event&&) = delete; + Event& operator = (Event&&) = delete; + ~Event() = default; + + //Create a EventHandlerPtr from the given handler, + //add it to list and return it. + EventHandlerPtr AddHandler(EventHandler&& handler) + { + EventHandlerPtr ptr = std::make_shared(std::move(handler)); + handlers_.push_back(ptr); + return ptr; + } + + void AddHandler(EventHandlerPtr handler) { + handlers_.push_back(handler); + } + + void RemoveHandler(EventHandlerPtr handler) { + auto find_result = std::find(handlers_.cbegin(), handlers_.cend(), handler); + if (find_result != handlers_.cend()) + handlers_.erase(find_result); + } + + void Raise(ArgsType& args) { + for (auto ptr : handlers_) + (*ptr)(args); + } + + private: + std::list handlers_; + }; +} -- cgit v1.2.3