Reputation: 2582
I'm wanting to implement some logging functions in a class I have here. Basically, my thought is to create a TStringList within the class which contains the log. I can do this without any trouble, but my question is how to expose it outside of the class in a way that a control (TMemo or TListBox) can dynamically show the contents if the containing form is present. I could make a direct association to the control within the class, but I'm wanting to keep the class discreet from the form code itself, and create a procedure in the class which makes this association.
Basically, if I have LogFile: TStringList in my class, how do I make it so adding a line there makes it show up in a TMemo from a form that is separate from the class?
Upvotes: 1
Views: 186
Reputation: 34929
Let the form register a callback event in your class.
If this event is assigned when adding an item to your list, use the callback to send the string.
Type
TMyCallback = procedure(const aLogStr: String) of object;
TMyClass = Class
private
FCallback : TMyCallback;
FLogFile : TStringList;
procedure SetCallback(ACallback: TMyCallback);
public
property Callback : TMyCallback write SetCallback;
end;
...
// Update FLogFile
FLogFile.Items.Add(SomeText);
if Assigned(FCallback) then
FCallBack(SomeText);
...
In your form class:
Type
TMyForm = Class(TForm)
private
procedure IncomingLogString(const AStr: String);
end;
procedure TMyForm.IncomingLogString(const AStr: String);
begin
MyMemo.Lines.Add(AStr);
end;
...
// Register callback
FMyClass.Callback := Self.IncomingLogString;
Now, your TMyClass
is decoupled from any dependence from the form.
Upvotes: 1