mirror of
https://github.com/gelldur/EventBus.git
synced 2024-12-26 18:51:02 +08:00
Add EventContainer for RAII
This commit is contained in:
parent
e23c3b2850
commit
d44c38d24e
40
src/EventContainer.cpp
Normal file
40
src/EventContainer.cpp
Normal file
@ -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(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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
58
src/EventContainer.h
Normal file
58
src/EventContainer.h
Normal file
@ -0,0 +1,58 @@
|
||||
//
|
||||
// Created by Dawid Drozd aka Gelldur on 18/10/16.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "Notifier.h"
|
||||
|
||||
namespace Dexode
|
||||
{
|
||||
|
||||
class EventContainer
|
||||
{
|
||||
public:
|
||||
EventContainer(const std::shared_ptr<Notifier>& 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<typename ... Args>
|
||||
void listen(const Notification<Args...>& notification
|
||||
, typename notifier_traits<const std::function<void(Args...)>&>::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<typename NotificationType, typename ... Args>
|
||||
void unlisten(const NotificationType& notification)
|
||||
{
|
||||
_notifier->unlisten(_token, notification);
|
||||
}
|
||||
|
||||
private:
|
||||
int _token = 0;
|
||||
std::shared_ptr<Notifier> _notifier;
|
||||
};
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user