Skip to content
Gautier Lefebvre edited this page Sep 21, 2016 · 2 revisions

Events in v0.2.0

You should read how the events work in v0.1.0 before reading this. A lot of it changed in v0.2.0.

Event declaration

The event declaration now takes the arguments of the callback function as template parameter.

You also no longer need to get the EventHandle object from its pool (it is no longer pooled to make it easier to use).

class Foo {
    // declare event (the anonymous struct is not mandatory)
    // in this case the event callback will be a function with a function<void (int, int)> prototype.
    struct {
        fwk::EventHandle<int, int> onChangeEvent;
    } events;

    Foo(void);
    ~Foo(void);
};

Declare event arguments

You don't need to declare the event arguments anymore.

Event subscription and unsubscription

At subscription you now give a callback with the arguments given as template parameter of the EventHandle.

class Bar {
    void init(const Foo&);
};
Bar::init(const Foo& foo) {
    foo.events.onChangeEvent.subscribe(
        [] (int a, int b) -> void {
            std::cout << "event fired" << std::endl;
            std::cout << "value A: " << a << std::endl;
            std::cout << "value B: " << b << std::endl;
        },     // callback
        this); // key
}

Event firing

Create the arguments

You no longer need to create the arguments wrapper. You now call the fireSync and fireAsync methods directly with the arguments.

Asynchronous

Foo foo;
Bar bar;

// subscribe to the event
bar.init(foo);

foo.events.onChangeEvent.fireAsync(10, 2);

Note that the above code would not work, since Foo and Bar wouldn't exist anymore when the callback is called (the event firing is added to the task queue).

Synchronous

Foo foo;
Bar bar;

// subscribe to the event
bar.init(foo);

foo.events.onChangeEvent.fireSync(10, 2);

This code would work since the callback would be called directly in fireSync.

Cleaning up asynchronous events and delayed tasks containing events.

Although you shouldn't use DelayedTask objects to fire events, there might be some use cases that require you to do so.

Bear in mind that upon destruction of the EventHandle object, any EventTask or DelayedTask containing this event will be removed from the task queue.

It is done automatically in the destructor, but you can also call directly the fwk::EventHandle::purgeTaskQueue() method to do so.

This way, the subscribers will not be notified of the event. This is done to prevent memory corruption and execution of events that no longer exist (therefore resulting in accessing invalid memory addresses).