The SRUtil.Event library designed for separation producers and consumers of events.
Event producers provide event_source
object. Event consumers
provide event_sink
(it may be callback interface, various kinds of
delegates etc).
Event producers and consumers may be bound by event_binder
.
event_source
and according event_binder
are
parametrized by sink_type
type, which must satisfy following
conditions:
sink_type()
produces empty value.
sink_type
has implicit conversation to bool
type.
Expression
if
(sink) {/*...*/}
allows execute code if
and only if sink
isn't empty value. Sink which bound with
something mustn't be converted to
true
.
Following entities satisfies these conditions: pointers (to object and to code),
boost::function
and srutil::delegate
.
A connection between event producer and event consumer exists since they are
bound by method event_binder::bind
until invokation of method event_binder::unbind
or destroying of event_binder
or event_source
.
A connection may be safely destroyed even during event emiting (binder may be
destroyed or unbound), but event_source
mustn't (in the current
implementation).
template <typename TSink> class event_source
{
public:
typedef TSink sink_type;
typedef event_binder<sink_type> binder_type;
template <class TInvoker>
void emit(TInvoker const& invoker);
};
template <typename TSink> class event_binder
{
public:
typedef TSink sink_type;
typedef event_source<sink_type> source_type;
void bind(event_source const& source, sink_type sink);
void unbind();
};
class EventListener
{
public:
virtual void someMethod(int, int) = 0;
};
typedef srutil::delegate<void (int, int)> Delegate;
typedef srutil::event_source<EventListener*> EventSource1;
typedef srutil::event_source<Delegate> EventSource2;
EventSource1 e1;
EventSource2 e2;
e1.emit(boost::bind(&EventListener::someMethod, _1, 5, 10));
e2.emit(Delegate::invoker_type(5, 10));