Improve a simple event handler
JN
666total at wp.pl
Sun Jan 16 20:01:09 UTC 2022
On Saturday, 15 January 2022 at 23:15:16 UTC, JN wrote:
>
> Is there some way I could improve this with some D features? My
> main gripes with it are:
>
Managed to dramatically simplify it to 10 lines of code with
variadic templates.
```d
import std.stdio;
struct Event(T...)
{
void function(T)[] listeners;
void addListener(void function(T) handler)
{
listeners ~= handler;
}
void emit(T args)
{
foreach (listener; listeners)
{
listener(args);
}
}
}
void onResize(uint newWidth, uint newHeight)
{
writefln("Resized: %d %d", newWidth, newHeight);
}
void main()
{
Event!(uint, uint) windowResizeEvent;
windowResizeEvent.addListener(&onResize);
windowResizeEvent.emit(1000, 2000);
}
```
I am very happy with this solution.
More information about the Digitalmars-d-learn
mailing list