mirror of
https://github.com/gelldur/EventBus.git
synced 2024-12-29 13:28:47 +08:00
fc1dbe335f
I was wondering if it is a good step for EventBus. Of course, it will break back compatibility again as well as it was when changing v1 -> v2, but this change is smaller. Those changes were inspired by Boost::MSM how it handles events. Why i decided to change: + It will prevent from bugs like typo in Event string eg. Event<int>{"text"} + If we want to change signature of Event, we won't have to update all listeners and their signature + Less includes for listener. Simply in our class header we will have eg. pointer/ref to event type not to all args + Strongly typed (this is always better) + Storing event for future reuse + More easy to introduce thread safe EventBus in future + EventBus is more simple + const Event forbids some kind of communication. Eg. passing and modifying reference + Less errors when using std::bind - Breaking back compatibility - Need fixes in projects that using this lib - Someone can add methods etc. to Event :( - We can't generate easily multiple "types" of events like in 'for' loop - Worst performance (still not such bad as CCNotificationCenter)
70 lines
1.1 KiB
C++
70 lines
1.1 KiB
C++
//
|
|
// Created by Dawid Drozd aka Gelldur on 18/10/16.
|
|
//
|
|
|
|
#pragma once
|
|
|
|
#include <memory>
|
|
|
|
#include "EventBus.h"
|
|
|
|
namespace Dexode
|
|
{
|
|
|
|
class EventCollector
|
|
{
|
|
public:
|
|
EventCollector(const std::shared_ptr<EventBus>& bus);
|
|
EventCollector(EventBus* bus);
|
|
EventCollector(EventCollector const& other);
|
|
EventCollector(EventCollector&& other);
|
|
|
|
~EventCollector();
|
|
|
|
EventCollector& operator=(EventCollector const& other);
|
|
EventCollector& operator=(EventCollector&& other);
|
|
|
|
/**
|
|
* Register listener for event.
|
|
*
|
|
* @tparam Event - type you want to listen for
|
|
* @param callback - your callback to handle event
|
|
*/
|
|
template<typename Event>
|
|
void listen(const std::function<void(const Event&)>& callback)
|
|
{
|
|
if (!callback || !_bus)
|
|
{
|
|
return;//Skip such things
|
|
}
|
|
if (_token == 0)
|
|
{
|
|
_token = _bus->listen<Event>(callback);
|
|
}
|
|
else
|
|
{
|
|
_bus->listen<Event>(_token, callback);
|
|
}
|
|
}
|
|
|
|
void unlistenAll();
|
|
|
|
/**
|
|
* @tparam Event - type you want to unlisten. @see Notiier::listen
|
|
*/
|
|
template<typename Event>
|
|
void unlisten()
|
|
{
|
|
if (_bus)
|
|
{
|
|
_bus->unlisten<Event>(_token);
|
|
}
|
|
}
|
|
|
|
private:
|
|
int _token = 0;
|
|
std::shared_ptr<EventBus> _bus;
|
|
};
|
|
|
|
}
|