[SOLVED] How to assign default event handler? lazarus / 21-General ---------------------------------------------------------------------- egsuh · 2021-03-07 00:35 Hi, Is this possible? I'd like to define default methods to events in a specific project.  Very simple example would be:     TreeView1.OnClick := TreeView1Click(Sender: TObject); Not in the object inspector, but in program codes. To extend this, I'm thinking putting this in type helper. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit raqFrame;type   HaqTreeView = class helper for TTreeView   public      function NewName: string;        procedure Click;  // <== Can I assign this function to OnClick event?    end; I want I don't have to define any more,  with just adding the unit containing helper type definition in the uses clause. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit fmain;interfaceuses  ...., raqFrame;  // <== Previous helper type is defined in the raqFrame unit.  type  TForm1 = class(TForm)    TreeView1: TTreeView;   // <== Here's TTreeView that access the helper type.   end; Of course, I can write : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.TreeView1Click(Sender: TObject);begin    TreeView1.Click;end; ---------------------------------------------------------------------- egsuh · 2021-03-07 13:26 QuoteI think what you are looking for Is to sub class some known classes and override existing events. ? No. Not exactly. Currently, I have to define "OnClick" event handler for any control, for example TEdit's onclick event.  Normally we do this in the object inspector, but we can assign this programmatically, like:      Edit1.Onclick := nil;           or      Edit1.OnClick := Edit1OnClick; What I'm looking for is assigning this automatically, within constructor, etc. I will be able to do this if I define a descendant class, like following example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i interface TMyEdit = Class(TEDIT)      Procedure DoClick(Sender:TObject);     constructor Create(Owner: TObject); override; End; implementation constructor TMyEdit.Create(Owner: TObject);begin       inherited Create(Owner);       OnClick:= DoClick; end; But in this case, I think I have to register TMyEdit on the component pallette. I'm looking for ways to do this without registering new component --- only using helpers. ---------------------------------------------------------------------- Zoran · 2021-03-07 13:32 Quote from: jamie on March 07, 2021, 04:31:45 am Any method existing in a class can be overridden .. Only virtual methods can be overridden. ---------------------------------------------------------------------- egsuh · 2021-03-08 01:31 I forgot that I cannot override creators.. they are not defined as virtual. Virtual creators are only needed when I use classref types. I cannot think of other cases that require virtual creators. ---------------------------------------------------------------------- Zoran · 2021-03-08 04:47 Quote from: egsuh on March 08, 2021, 02:31:59 amI forgot that I cannot override creators.. they are not defined as virtual. Virtual creators are only needed when I use classref types. I cannot think of other cases that require virtual creators. But in your example, it is virtual and you can override it. TEdit is derived from TComponent. ---------------------------------------------------------------------- lucamar · 2021-03-08 09:34 Quote from: egsuh on March 08, 2021, 02:31:59 amI forgot that I cannot override creators.. they are not defined as virtual. Virtual creators are only needed when I use classref types. I cannot think of other cases that require virtual creators. You'll discover that most constructors (and destructors) are in fact virtual precisely for this reason, so that one can derive a new subclass and initialize new fields or modify the default ones on the base class. That's why most implementations of derived classes start (or end, in destructors) with inherited ---------------------------------------------------------------------- Sieben · 2021-03-08 10:13 Quote from: Zoran on March 07, 2021, 02:32:47 pmQuote from: jamie on March 07, 2021, 04:31:45 am Any method existing in a class can be overridden .. Only virtual methods can be overridden. A static method can be 'sort of' overridden, however. You cannot use keyword override but you can create an new method of the same name and you can even call inherited from within this new method. Drawback is that you need to explicitely call the instance by it's new class name (otherwise it would call the method of the ancestor class called), but in case of creators this the case anyway. TObject.Create is not virtual, btw. ---------------------------------------------------------------------- lucamar · 2021-03-08 10:43 Quote from: Sieben on March 08, 2021, 11:13:38 amA static method can be 'sort of' overridden, however. You cannot use keyword override but you can create an new method of the same name [...] What you're doing then is reintroducing the method, and the new one (if it's not an overload) will hide the previous one from then on. This can also be done with virtual methods, though then you have to use an explicit reintroduce modifier. Note that calling inherited from such a method can produce strange effects and might not work as you think in different versions of the compiler. Quote from: Sieben on March 08, 2021, 11:13:38 amTObject.Create is not virtual, btw. Probably because it does nothing other than call NewInstance in hidden, compiler-internal code, which is done for all classes. Being the common ancestor for all classes, TObject is somewhat "special" in many ways. ---------------------------------------------------------------------- howardpc · 2021-03-08 13:39 Quote from: Sieben on March 08, 2021, 11:13:38 amA static method can be 'sort of' overridden, however. You cannot use keyword override but you can create an new method of the same name ... I think it is extremely confusing to use the term "overridden" in this situation, since in well-designed object-oriented code "override" has a clear and specific meaning, namely that this unique method name will be implemented differently in this descendant from how the identically-named method is implemented in its ancestor(s), and that the overridden method may, or may not, include inherited code. Even the term "reintroduce" (which derives from Delphi) is somewhat misleading, since although it could be said that you are reintroducing the method name, what is more to the point is that you are redefining the method, albeit confusingly reusing a name that means something different in the ancestral hierarchy. I cannot conceive of a situation in which a programmer has no option but to redefine methods in a well-designed hierarchy in this way, particularly in an English-based language such as Object Pascal where the mother tongue has such a superfluity of synonyms for virtually every term in common use. To deliberately reuse a method name to mean two things at the same time in the same code seems to me pointlessly confusing, and a mark of poor design. Programmers are restricted by the syntax and grammar of the language they choose. Intelligent choice of method (and other) identifiers  can make the code virtually self-explanatory, and sloppy naming can obfuscate it and give rise to all kinds of debugging difficulties. ---------------------------------------------------------------------- lucamar · 2021-03-08 13:50 Quote from: howardpc on March 08, 2021, 02:39:57 pmI cannot conceive of a situation in which a programmer has no option but to redefine methods in a well-designed hierarchy in this way, [...] Very few, granted, but some times one has no other option than to completely redefine a method, if for nothing else than to have a descendant with a completely different behaviour. One can't always avoid having to inject a subclass that way and not always is the class hierarchy under your full control. And once or twice I have had to use reintroduce to work around a Delphi inconsistency. Ok, maybe once or twice in 30+ years is not much, but there it is ---------------------------------------------------------------------- Zoran · 2021-03-09 09:39 Quote from: Sieben on March 08, 2021, 11:13:38 amTObject.Create is not virtual, btw. In egsuh's example, the constructor he tries to override is TComponent.Create(Owner: TObject). And it is virtual. ---------------------------------------------------------------------- Sieben · 2021-03-09 12:37 Absolutely correct, as is your statement that only virtual methods can be overridden, of course. I just wanted to mention that you can take similar - but not equal - action with static methods as well if you are aware of the drawbacks. There seems to be a bit of confusion on the use of inherited with static methods but that should be discussed in another thread then. ---------------------------------------------------------------------- Sieben · 2021-03-09 15:53 Back to OP's question (and sorry for sort of abusing your thread). If you want to assign methods to component events you might want to use code like this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // on a TForm call like GrabEvents(Self, 'OnMouseEnter', TMethod(@ComponentsMouseEnter)) procedure GrabEvents(AContainer: TComponent; AnEventName: string; AnEvent: TMethod);var i: Integer;begin  with AContainer do    for i:=0 to pred(ComponentCount) do      if Assigned(GetPropInfo(Components[i],AnEventName)) then      SetMethodProp(Components[i],AnEventName,AnEvent);end; This assigns a single event to all components on your form which for example expose OnMouseEnter. It can be easily modified to assign an event to only TEdits, for example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i // within eg TForm.OnCreate call like GrabEvents(Self, TEdit, 'OnClick', TMethod(@EditsClick)) procedure GrabEvents(AContainer: TComponent; AClass: TClass; AnEventName: string; AnEvent: TMethod);var i: Integer;begin  with AContainer do    for i:=0 to pred(ComponentCount) do      if Components[i] is AClass      and Assigned(GetPropInfo(Components[i],AnEventName)) then        SetMethodProp(Components[i],AnEventName,AnEvent);end; That way you only need to call this procedure once in eg TForm.OnCreate to have all your TEdits connected to a single OnClick event. If you want only certain TEdits to be connected you can use the Tag property for example. Edit: forgot to mention that you need to add TypInfo to your uses clause. ---------------------------------------------------------------------- eny · 2021-03-09 18:05 Quote from: egsuh on March 07, 2021, 02:26:40 pmWhat I'm looking for is assigning this automatically, within constructor, etc. If you want to customize the behavior of such a standard component, then you would typically create a Decorator (https://en.wikipedia.org/wiki/Decorator_pattern). For example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit uEditDecorator;{$mode objfpc}{$H+}interface uses  Classes, SysUtils, StdCtrls; type  { TEditDecorator }  TEditDecorator = class(TComponent) // TComponent so it's auto-freed on form destruction  private    FEdit: TEdit;  public    constructor Create(pOwner: TComponent; pAssociated: TEdit); reintroduce;    destructor Destroy; override;    procedure OnEditClick(Sender: TObject);  end; implementation constructor TEditDecorator.Create(pOwner: TComponent; pAssociated: TEdit);begin  inherited Create(pOwner);  FEdit := pAssociated;  if assigned(FEdit) then    FEdit.OnClick := @OnEditClick;end; destructor TEditDecorator.Destroy;begin  if assigned(FEdit) then    FEdit.OnClick := nil;  inherited Destroy;end; procedure TEditDecorator.OnEditClick(Sender: TObject);begin  FEdit.Text := 'Clicked...';end; end. And then use it as: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TfrmMain.FormCreate(Sender: TObject);begin  TEditDecorator.Create(self, Edit1);end; ---------------------------------------------------------------------- Remy Lebeau · 2021-03-09 18:23 Quote from: egsuh on March 07, 2021, 02:26:40 pmWhat I'm looking for is assigning this automatically, within constructor, etc. I will be able to do this if I define a descendant class, like following example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i interface TMyEdit = Class(TEDIT)      Procedure DoClick(Sender:TObject);     constructor Create(Owner: TObject); override; End; implementation constructor TMyEdit.Create(Owner: TObject);begin       inherited Create(Owner);       OnClick:= DoClick; end; DoClick() is a virtual method that fires the OnClick event.  The whole point of having such a virtual method is so that you don't have to assign an event handler at all, just override the virtual method instead, eg: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i interface type  TMyEdit = class(TEdit)     procedure DoClick; override;  end; implementation procedure TMyEdit.DoClick;begin   // do your work here as needed...  // if desired, call inherited to fire the OnClick event... end; Most components have virtual event firers for exactly this reason. Quote from: egsuh on March 07, 2021, 02:26:40 pmBut in this case, I think I have to register TMyEdit on the component pallette. I'm looking for ways to do this without registering new component --- only using helpers. Then you can define your class to be an interposer instead.  An interposer is a class that derives from another class in a different unit, and has the same name as the class it is deriving from, eg: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i interface type  TEdit = class(StdCtrls.TEdit)     procedure DoClick; override;  end; implementation procedure TEdit.DoClick;begin   // do your work here as needed...  // if desired, call inherited to fire the OnClick event... end; This way, if you place your unit in another unit's uses clause after the StdCtrls unit, then the compiler will use your TEdit class automatically, instead of using the standard TEdit class, eg: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses  ..., StdCtrls, ..., MyUnit; type  TSomeForm = class(TForm)    Edit1: TEdit; // <=-- will use MyUnit.TEdit, not StdCtrls.TEdit!    ...  end; ---------------------------------------------------------------------- egsuh · 2021-03-10 02:41 @Remy Lebeau, Really thank you for our explanations. They made a lot of things clear (within my head). Reality is TEdit.Click instead of TEdit.DoClick, but anyway I could interpose it. Overing virtual methods does not work in helper types --- I have to assign Edit1.Onclick if I use helper. But anyway I have a few options that will make codes much neater.  I'll buy you a glass of Remy Martin XO if I see you^^ ---------------------------------------------------------------------- egsuh · 2021-03-10 02:54 FYI, I tested followings --- not using separate unit, but re-declaring within the same unit. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit fmain; interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls;  type  TEdit = class(StdCtrls.TEdit)    procedure Click; override;  end;   TForm1 = class(TForm)      Edit1: TEdit;  end; var  Form1: TForm1; implementation {$R *.lfm} procedure TEdit.Click;begin   // inherited Click;   showmessage('Hello');end; end.  I think this is quite convenient, if used carefully within frames, etc.