Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnClick event override

I have my custom class witch is derived from TButton:

TLoginResultEvent = procedure (Sender: TObject; LoginResult: boolean) of object;
TLoginButton = class(TButton)
    private
      fLogin: TLoginChooser;
      fOnClick: TLoginResultEvent;
    public
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;

      procedure OnClickResult(Sender: TObject; LoginResult: boolean);
    published
      property Login: TLoginChooser read fLogin write fLogin;
      property OnClick: TLoginResultEvent read fOnClick write fOnClick;
  end;

in constructor I added:

constructor TLoginButton.Create(AOwner: TComponent);
begin
  inherited;

  fOnClick := OnClick;
  OnClick := OnClickResult;
end;

But when I click on the button it's not firing OnClickResult, what am I doing wrong? Is it possible to "override" OnClick event handler or should I hide it and make for example OnResultClick event?

like image 332
JustMe Avatar asked May 16 '11 16:05

JustMe


1 Answers

When writing components, you should not use the event handlers to implement custom behaviour. Instead you should override the code calling these event handlers. In this case, forget about setting OnClick. Instead, simply add

public
  procedure Click; override;

to your class declaration, and implement

procedure TLoginButton.Click;
begin
  inherited; // call the inherited Click method.
  // Do something new.
end;

The event handlers are there to be used by the developer using the component. The component writer should not use them herself.

If you want the component user to see a different 'OnClick' method, you have to implement this yourself, like

type
  TLoginResultEvent = procedure(Sender: TObject; LoginResult: boolean) of object;

...

TLoginButton = class(TButton)
private
  FOnClick: TLoginResultEvent;
...
public
  procedure Click; override;
...
published
  property OnClick: TLoginResultEvent read FOnClick write FOnClick;
...

procedure TLoginButton.Click;
begin
  inherited;
  if Assigned(FOnClick) then
    FOnClick(Self, true); // or false...
end;
like image 73
Andreas Rejbrand Avatar answered Oct 12 '22 23:10

Andreas Rejbrand