delphi – VCL events with anonymous methods – what do you think about this implementation? – Stack Overflow
Posted by jpluimers on 2017/10/19
A long time ago, Pablo Vizcay a.k.a. [WayBack] pragmatic_programmer wrote some cool code at [WayBack] delphi – VCL events with anonymous methods – what do you think about this implementation? – Stack Overflow.
I still think it’s a very neat solution to bind method references to events.
type TNotifyEventDispatcher = class(TComponent) protected FClosure: TProc<TObject>; procedure OnNotifyEvent(Sender: TObject); public class function Create(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent; overload; function Attach(Closure: TProc<TObject>): TNotifyEvent; end; implementation class function TNotifyEventDispatcher.Create(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent; begin Result := TNotifyEventDispatcher.Create(Owner).Attach(Closure) end; function TNotifyEventDispatcher.Attach(Closure: TProc<TObject>): TNotifyEvent; begin FClosure := Closure; Result := Self.OnNotifyEvent end; procedure TNotifyEventDispatcher.OnNotifyEvent(Sender: TObject); begin if Assigned(FClosure) then FClosure(Sender) end; end.
And this is how it’s used for example:
procedure TForm1.FormCreate(Sender: TObject); begin Button1.OnClick := TNotifyEventDispatcher.Create(Self, procedure (Sender: TObject) begin Self.Caption := 'DONE!' end) end;
–jeroen






jpluimers said
Via G+: https://plus.google.com/+JeroenPluimers/posts/HgeCrVYT3SH
Lars Fosdal
The problems occur when the capture contains references that change. Something that will not show as a hint or warning.