Chapter 21. Event callbacks

Index

Using the same callback objects for multiple callbacks

The event callback framework is a lightweight alternative to an event factory which does not use a registration handle. Rather, a callback object gets registered, and it remains registered and receives events until the callback object goes out of scope and gets destroyed, at which point it, naturally, stops receiving events.

class mycbObj : public x::eventcallback<int>::baseObj {

public:
	int sum;

	mycbObj() : sum(0)
	{
	}

	~mycbObj() noexcept
	{
	}

	void event(const int &n)
	{
		sum += n;
	}
};

typedef x::ptr<mycbObj> mycb;

x::eventcallback<int> callback_list;

mycb cb(mycb::create());

// ...

callback_list.install(cb);

// ...

callback_list.event(3);

The parameter to the x::eventcallback is the type of the argument that's received by registered callbacks. The argument gets passed to the eventcallback's event() method.

The reference-counted. callback objects must be subclassed from eventcallback<argtype>::baseObj, and all registered callback objects' event() methods get invoked and receive the event argument.

The x::eventcallback<void> specialization defines a callback mechanism without any arguments. It's event() method, and the virtual event() in baseObj does not take arguments.

Using the same callback objects for multiple callbacks

It's possible to invoke a different method than event() in a callback object, and have different methods in the same callback object used by different callback notifications.

class customcbObj : virtual public x::obj {

public:

	int sum;

	customcbObj() : sum(0)
	{
	}

	~customcbObj() noexcept
	{
	}

	void event_int(int n)
	{
		sum += n;
	}

	void event_void()
	{
		sum = -sum;
	}
};

typedef x::ptr<customcbObj> customcb;

class invoke_int {

public:

	static void event(const x::ptr<customcbObj> &cb,
			  int arg)
	{
		cb->event_int(arg);
	}
};

class invoke_void {

public:

	static void event(const x::ptr<customcbObj> &cb)
	{
		cb->event_void();
	}
};

// ...

customcb cb(customcb::create());

x::eventcallback<int, customcbObj, invoke_int> cb_int;

x::eventcallback<void, customcbObj, invoke_void> cb_void;

cb_int.install(cb);
cb_void.install(cb);

cb_int.event(4);
cb_void.event();

The second template to eventcallback specifies the callback class name (which gets typedefed to the baseObj member class). The third parameter is a class that implements a static event() method that receives a reference to a registered callback object, and the callback argument (if it's not a void callback).

The above example implements two callbacks that may be used with the same handler, one that takes an int argument and one that takes no arguments.