I'm having a form with certain components whose are having event handlers. Now I would like to move those event handlers (those methods) to a separate unit still being able to assign them to component events through the Object Inspector at design time.
Is it possible to make a separate unit only for event methods, so that the Object Inspector allows me to assign them at design time ?
Let's say if I would make that unit with a public procedure:
unit Unit2;
interface
procedure ButtonClick(Sender: TObject);
implementation
procedure ButtonClick(Sender: TObject);
begin
// do something here
end;
end.
Or with a class with published method like this:
unit Unit2;
interface
type
TMyClass = class
published
procedure ButtonClick(Sender: TObject);
end;
var
MyClass: TMyClass;
implementation
{ TMyClass }
procedure TMyClass.ButtonClick(Sender: TObject);
begin
// do something here
end;
end.
How to make a separate unit for event methods, which IDE allows me to assign to component events at design time ? Like for instance:
Most events are method pointers. That means they point to a procedure or function in a class. So you cannot just attach the procedure Unit2.ButtonClick to an on click event of a button, but you can write a class that implements the event handler, something like this:
type
TMainFormButtonEventHandler = class
procedure ButtonClick(Sender: TObject);
end;
procedure TMainFormButtonEventHandler.ButtonClick(Sender: TObject);
begin
ShowMessage('Clicked');
end;
Now you can create such an object and link it to the event:
handler := TMainFormButtonEventHandler.Create;
Form1.Button1.OnClick := handler.ButtonClick;
I don't think this is the best application structure, though. I would not hook into GUI elements of a form from outside the form's unit. But if you would like to do so, this is how it's done.
If you're looking for separation of GUI and logic, have a look at actions. A TAction (wrapped in an ActionList), is the first layer of abstration between a GUI component like a button and the action code it performs.
The convenient thing is that you can create those actions at design time as well, and attach them to a button or other control. Instead of writing code for ButtonClick, you write code for ActionExecute (the OnExecute event of the action). The button knows that when it is clicked, it should execute its related action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With