Improve a simple event handler

Sebastiaan Koppe mail at skoppe.eu
Mon Jan 17 12:57:52 UTC 2022


On Sunday, 16 January 2022 at 20:01:09 UTC, JN wrote:
> 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.

Looks good. But do note that with larger applications it 
inevitably becomes a ball of spaghetti, making it hard to 
understand why a certain widget behaves the way it does (or 
doesn't).

The other problem - already apparent in this small example - is 
the absence of `removeListener`. It is a very crucial and often 
overlooked part that often only gets written afterwards. The 
problem is that it ties into lifetime which is hard to bolt on.

For small things though, it works wonderfully.


More information about the Digitalmars-d-learn mailing list