Signal

This Signal struct is an implementation of the Observer pattern.

All D callable types (functions, delegates, structs with opCall, classes with opCall) can be registered with a signal. When the signal occurs all assigned callables are called.

Structs with opCall are only supported if they're passed by pointer. These structs are then expected to be allocated on the heap.

Delegates to struct instances or nested functions are supported. You have to make sure to disconnect these delegates from the Signal before they go out of scope though.

The return type of the handlers must be void or bool. If the return type is bool and the handler returns false the remaining handlers are not called. If true is returned or the type is void the remaining handlers are called.

SafeD: This Signal template can be used in safeD; all public functions are @safe or @trusted. All handlers connected to a signal must be @safe or @trusted. It's currently not possible to enforce the safety of the handlers, but it will be enforced as soon as possible.

Members

Functions

calculateLength
uint calculateLength()

Calculate the number of registered handlers

clear
void clear()

Remove all handlers from the signal

connect
T connect(T handler)

Add a handler to the list of handlers to be called when emit() is called. The handler is added at the end of the list.

connectAfter
T connectAfter(T afterThis, U handler)

Add a handler to be called after another handler.

connectBefore
T connectBefore(T beforeThis, U handler)

Add a handler to be called before another handler.

connectFirst
T connectFirst(T handler)

Add a handler to the list of handlers to be called when emit() is called. Add this handler at the top of the list, so it will be called before all other handlers.

disconnect
T disconnect(T handler)

Remove a handler from the list of handlers to be called when emit() is called.

emit
void emit(Types params)

Call the connected handlers as explained in the documentation for the signal struct.

isConnected
bool isConnected(T handler)

Check whether a handler is already connected

opCall
void opCall(Types params)

Just like emit()

opOpAssign
T opOpAssign(T rhs)

Just like Signal.connect()

Variables

enabled
bool enabled;

Set to false to disable signal emission

Examples

import std.stdio;
import std.signals;

//same for classes
struct A
{
    string payload;
    @safe bool opCall(float f, string s)
    {
        writefln("A: %f:%s:%s", f, s, payload);
        return true;
    }
}

@safe void testFunc(float f, string s)
{
     writefln("Function: %f:%s", f, s);
}

Signal!(float, string) onTest;

void main()
{
    A* a = new A();
    a.payload = "test payload";
    onTest.connect(a);
    onTest ~= &testFunc;
    onTest(0.123f, "first call");
}

Meta