...
TForm1 = class(TForm,IFPObserver) // <==
Edit1: TEdit;
Edit2: TEdit;
procedure EditChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
public
procedure FPOObservedChanged(ASender: TObject; Operation: TFPObservedOperation;Data: Pointer);
end;
...
implementation
...
procedure TForm1.FormCreate(Sender: TObject);
begin
// here we attach ourselves to the Edit1's IFPObserved subject, meaning
Edit1.FPOAttachObserver(Self); // "please notify us"
Edit2.FPOAttachObserver(Self);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
// it's pretty _important_ to detach ourselves again, when we're done
// listening, to avoid dangling references AV's
// todo: search if there a way to check if an observer is attached?
Edit1.FPODetachObserver(Self);
Edit2.FPODetachObserver(Self);
end;
procedure TForm1.EditChange(Sender: TObject);
var
aEdit : TEdit;
begin
if Sender is TEdit then
begin
aEdit := (Sender as TEdit);
// here we utilize the built-in observer-pattern, namely IFPObserved
// to notify everybody, who might be attached to observe aEdit
// TFPObservedOperation = (ooChange,ooFree,ooAddItem,ooDeleteItem,ooCusto
aEdit.FPONotifyObservers(aEdit,ooChange,pchar(aEdit));
// we send aEdit in the ASender param, ooChange because aEdit is
// changing and typecast aEdit.Text string to a pchar, so we can send it
// in a pointer variable
end;
end;
// here we implement the only method in IFPObserver (the listener)
// it can observe mutiple "subjects", by attaching iself to them
procedure TForm1.FPOObservedChanged(ASender: TObject;
Operation: TFPObservedOperation; Data: Pointer);
var
aEdit : TEdit;
s : String;
begin
// TFPObservedOperation is an enumerated type, thus we can use 'case'
case Operation of
ooCustom: ; // a 'TButton' might send us custom operations...
// because we can handle multiple subjects, we check what's been sent
ooChange: begin // to us and from whom -> 'ASender'
if ASender is TEdit then
begin
aEdit := (ASender as TEdit);
s := aEdit.Name; // just to see in the watchlist the edit.name
if aEdit = Edit1 then
Caption:= pchar(Data) // <== Gets here but Form.caption is changes to empty and not to the edit text.
else if aEdit = Edit2 then
Caption:= pchar(Data) // <== Gets here but Form.caption is changes to empty and not to the edit text.
end
end;
// we know that, in this case, Edit1 sends us text disguised as a pchar
ooAddItem: ; // a list might notify us, of an added item etc...
end;
end;
end.