From d44c38d24e685da1d8ac89e710a8b26f6a93f492 Mon Sep 17 00:00:00 2001 From: Dawid Drozd Date: Tue, 18 Oct 2016 21:48:44 +0200 Subject: [PATCH] Add EventContainer for RAII --- src/EventContainer.cpp | 40 +++++++++++++++++++++++++++++ src/EventContainer.h | 58 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 src/EventContainer.cpp create mode 100644 src/EventContainer.h diff --git a/src/EventContainer.cpp b/src/EventContainer.cpp new file mode 100644 index 0000000..d128db5 --- /dev/null +++ b/src/EventContainer.cpp @@ -0,0 +1,40 @@ +// +// Created by Dawid Drozd aka Gelldur on 18/10/16. +// + +#include "EventContainer.h" + +namespace Dexode +{ + +EventContainer::EventContainer(const std::shared_ptr& notifier) + : _notifier(notifier) +{ + assert(_notifier); +} + +void null_deleter(Notifier*) +{ +} + +//Maybe ugly but hey ;) Less code and simply i can :D +EventContainer::EventContainer(Notifier& notifier) + : _notifier(¬ifier, &null_deleter) +{ + assert(_notifier); +} + +EventContainer::~EventContainer() +{ + unlistenAll(); +} + +void EventContainer::unlistenAll() +{ + if (_token != 0) + { + _notifier->unlistenAll(_token); + } +} + +} diff --git a/src/EventContainer.h b/src/EventContainer.h new file mode 100644 index 0000000..7036acd --- /dev/null +++ b/src/EventContainer.h @@ -0,0 +1,58 @@ +// +// Created by Dawid Drozd aka Gelldur on 18/10/16. +// + +#pragma once + +#include + +#include "Notifier.h" + +namespace Dexode +{ + +class EventContainer +{ +public: + EventContainer(const std::shared_ptr& notifier); + EventContainer(Notifier& notifier = Notifier::getGlobal()); + + ~EventContainer(); + + /** + * Register listener for notification. Returns token used to unregister + * + * @param notification - pass notification like "getNotificationXYZ()" + * @param callback - your callback to handle notification + */ + template + void listen(const Notification& notification + , typename notifier_traits&>::type callback) + { + if (_token == 0) + { + _token = _notifier->listen(notification, callback); + } + else + { + _notifier->listen(_token, notification, callback); + } + } + + void unlistenAll(); + + /** + * @param notification - notification you wan't to unlisten. @see Notiier::listen + */ + template + void unlisten(const NotificationType& notification) + { + _notifier->unlisten(_token, notification); + } + +private: + int _token = 0; + std::shared_ptr _notifier; +}; + +}