Signals and Slots in D

Fredrik Olsson peylow at gmail.com
Fri Sep 29 01:41:48 PDT 2006


Walter Bright skrev:
> Fredrik Olsson wrote:
>> I like what I see. But there is a problem, a signal is hereby 
>> identified by it's types only. In a real world scenario many signals 
>> will have the same types. Bith a keyUp and a keyDown signal will 
>> probably want to send  a key code of the same type.
> 
> I don't understand the problem.
Lets say you have a UI control that can emit two signals; Click and 
DoubleClick, both send the mouse button as argument.

enum MouseButton { LEFT = 0, RIGHT = 1, MIDDLE = 3 };

class MyControl {
   mixin Signal!(MouseButton);

   void myActualClick(MouseButton mb) {
     ...
     emit(mb);
   }

   void myActualDoubleClick(MouseButton mb) {
     ...
     emit(mb);
   }

}


For the signal targets it will be impossible to tell a click from a 
double click. Unless you pass a more arguments, but then you kind of 
loose the simple idea of connecting to listen to a single event signal.

But I think this is more easily solved using "informal interfaces" that 
can have optional methods, and object delegates listening for the events 
instead of complex S&S.


enum MouseButton { LEFT = 0, RIGHT = 1, MIDDLE = 3 };

interface MyControlDelegate {
   optional void click(MyControl, MouseButton);
   optional void doubleClick(MyControl, MouseButton);
   optional bool shouldEnable(MyControl) = true;
}

class MyControl {
   MyControlDelage delegate;

   ...

   void myActualClick(MouseButton mb) {
     ...
     delegate.click(this, mb);
   }

   void myActualDoubleClick(MouseButton mb) {
     ...
     delegate.doubleClick(this, mb);
   }

   void myActualTestForEnabled() {
     this.enabled = delegate.shouldEnable(this);
   }

}

class MyActualDelegate : MyControlDelegate {
   bool shouldEnable(MyControl) {
     return today() is TUESDAY;
   }
}

MyControl cnt = new MyControl();
cnt.delegate = new MyActualDelegate(); // Add "automagic" enabling.

The deleagtes will probably not be such specific objects, but rather 
some larger business logic objects.

So an "informal interface" is a interface of methods that could be 
implemented, not an interface of methods that must be implemented. The 
methods are virtual, so testing for implementation should be as easy as 
comparing for NULL in the VMT.



// Fredrik Olsson



More information about the Digitalmars-d mailing list