Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1440

delphi – VCL events with anonymous methods – what do you think about this implementation? – Stack Overflow

$
0
0

A long time ago, Pablo Vizcay a.k.a. [WayBackpragmatic_programmer wrote some cool code at [WayBackdelphi – 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


Filed under: Delphi, Delphi 10 Seattle, Delphi 10.1 Berlin (BigBen), Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Delphi XE5, Delphi XE6, Delphi XE7, Delphi XE8, Development, Software Development

Viewing all articles
Browse latest Browse all 1440

Trending Articles