Override the OnClick event

I have my own custom class 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 the constructor, I added:

 constructor TLoginButton.Create(AOwner: TComponent); begin inherited; fOnClick := OnClick; OnClick := OnClickResult; end; 

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

+6
source share
1 answer

When writing components, you should not use event handlers to implement custom behavior. Instead, you should override the code that calls these event handlers. In this case, forget about setting OnClick . Instead, just add

 public procedure Click; override; 

into the class declaration and implement

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

Event handlers must be used by the developer using the component. The component writer should not use them on their own.

If you want the component user to see another OnClick method, you must implement this yourself, for example

 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; 
+12
source

Source: https://habr.com/ru/post/888241/


All Articles