Signals and Slots in D

Lutger lutger.blijdestijn at gmail.com
Thu Sep 28 20:04:33 PDT 2006


Walter Bright wrote:
> Walter Bright wrote:
>> Some of the boilerplate can be eliminated with a mixin.
> 
> Here's the mixin. Actually, 3 of them, one each for 0 arguments, 1 
> argument, and 2 arguments. I added a disconnect() function. Note how 
> trivial it is to use - no need for preprocessing.

Nice, this is also a good option imho, even though it lacks a few 
features. To be fair, the preprocessor of QT adds a lot more stuff than 
this. See 
http://www.scottcollins.net/articles/a-deeper-look-at-signals-and-slots.html 
for a comparison.

I would mix this in a struct, alias emit to opCall, provide a clear 
function (remove all delegates) and maybe opApply. Then you can have 
something like this:

class Button
{
     Signal!() onClicked;
     void processInput()
     {
         if (/*code to detect clicky*/)
             onClicked();
     }
}

Button clicky = new Button;
Popup hello = new Popup("hello");
clicky.onClicked.connect(&hello.msg);
// or clicky.onClicked.connect(&hello.msg, hello) if connections are 
made safe.
// or: clicky.onClicked ~= hello.msg;

If and when D function pointers and delegates get to be compatible, 
(will they?) it will get even better for this simple solution.



More information about the Digitalmars-d mailing list