I'm trying to create a class in a Delphi 12 application to manage a certain type of data in my application. The app has two sets of this data, so that's why I'm making a class and abstracting the properties and methods of the data.
I followed the code in Delphi event handling, how to create own event to create the class shown below:
unit PathList;
//https://stackoverflow.com/questions/5786595/delphi-event-handling-how-to-create-own-event?rq=3
interface
Type
TListChangedEvent = procedure(Sender: TObject) of object;
TPathList = Class
private
FListChangedEvent: TListChangedEvent;
FPathType: String;
FSize: Integer;
public
property ListChangedEvent: TListChangedEvent read FListChangedEvent
write FListChangedEvent;
constructor Create(pathType: String);
property Size: Integer read FSize;
property pathType: String read FPathType;
protected
procedure DoListChangedEvent(Sender: TObject);
private
end;
implementation
{ TPathList }
procedure TPathList.DoListChangedEvent(Sender: TObject);
begin
if Assigned(FListChangedEvent) then
FListChangedEvent(self);
end;
constructor TPathList.Create(pathType: String);
// must call the constructor to set the path type
begin
FPathType := pathType;
end;
end.
What I can't figure out, and what I can't find an example of, is how do I create the event listener in another unit in my app? Can someone please show me how?
Simply declare a class procedure of matching signature, and assign it to the event like any other variable, ie:
uses
PathList;
type
SomeOtherClass = class(...)
private
FList: TPathList;
procedure ListChanged(Sender: TObject);
...
public
constructor Create(...);
destructor Destroy; override;
end;
constructor SomeOtherClass.Create(...);
begin
...
FList := TPathList.Create;
FList.ListChangedEvent := ListChanged;
...
end;
destructor SomeOtherClass.Destroy;
begin
...
FList.Free;
inherited;
end;
procedure SomeOtherClass.ListChanged(Sender: TObject);
begin
// do something...
end;