View previous topic :: View next topic |
Author |
Message |
Bojo
Joined: 22 Oct 2004 Posts: 23 Location: Denmark
|
Posted: Thu Nov 11, 2004 5:18 pm Post subject: Delegates in event handlers |
|
|
In the examples included with DFL, I've noticed that you can assign an event handler in two ways. Either by using a function or a delegate.
When should I use a function and when should I use a delegate? In some cases I can't make it work with a delegate, whereas it works just fine with a function.
I've made the following useless flashing-label class. If I change the onFlash function into a delegate, the label won't flash anymore. How come?
Code: | module flashinglabel;
private import dfl.base, dfl.control, dfl.winapi, dfl.application;
private import dfl.event, dfl.timer, dfl.label;
class FlashingLabel: Label
{
final void interval(DWORD timeout) // setter
{
timer.interval = timeout;
}
final DWORD interval() // getter
{
return timer.interval;
}
final void flashing(bit flash) // setter
{
if (flash)
startFlashing();
else
stopFlashing();
}
final bit flashing() // getter
{
return labelFlashing;
}
final void startFlashing()
{
timer.start();
labelFlashing = true;
}
final void stopFlashing()
{
timer.stop();
labelFlashing = true;
visible = true;
}
this()
{
timer = new Timer;
timer.tick ~= &onFlash;
startFlashing();
}
~this()
{
timer.stop();
}
protected:
void onFlash(Object sender, EventArgs ea)
{
visible = !visible;
}
private:
Timer timer;
bit labelFlashing = true;
}
|
|
|
Back to top |
|
|
Chris Miller
Joined: 27 Mar 2004 Posts: 514 Location: The Internet
|
Posted: Sun Nov 14, 2004 2:08 pm Post subject: |
|
|
Non-static member functions are delegates. You're probably referring to a literal delegate with the delegate keyword. Delegate literals only work if you're sure the event won't be fired after the function it's in returns. |
|
Back to top |
|
|
Bojo
Joined: 22 Oct 2004 Posts: 23 Location: Denmark
|
Posted: Sun Nov 14, 2004 5:09 pm Post subject: |
|
|
Vathix wrote: | Non-static member functions are delegates. You're probably referring to a literal delegate with the delegate keyword. Delegate literals only work if you're sure the event won't be fired after the function it's in returns. |
Ok, that explains why it wouldn't work in my class. Thanks. |
|
Back to top |
|
|
|