diff options
author | crupest <crupest@outlook.com> | 2018-09-01 23:28:28 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2018-09-01 23:28:28 +0800 |
commit | 956a401f9c955f26b7e661dc80f76bfc43fc4124 (patch) | |
tree | 8af088933c7bc08942478daddd55c92de8668359 /CruUI/cru_event.h | |
download | cru-956a401f9c955f26b7e661dc80f76bfc43fc4124.tar.gz cru-956a401f9c955f26b7e661dc80f76bfc43fc4124.tar.bz2 cru-956a401f9c955f26b7e661dc80f76bfc43fc4124.zip |
Initial commit
Diffstat (limited to 'CruUI/cru_event.h')
-rw-r--r-- | CruUI/cru_event.h | 86 |
1 files changed, 86 insertions, 0 deletions
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 <type_traits> +#include <list> +#include <memory> +#include <algorithm> + +#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<typename TArgsType> + class Event + { + public: + static_assert(std::is_base_of_v<BasicEventArgs, TArgsType>, + "TArgsType must be subclass of BasicEventArgs."); + + + using ArgsType = TArgsType; + using EventHandler = Action<ArgsType&>; + using EventHandlerPtr = std::shared_ptr<EventHandler>; + + 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<EventHandler>(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<EventHandlerPtr> handlers_; + }; +} |