Author: Tomas Rutkauskas
I have a frame with two panels on it (right and left). The left panel is a pretty
standard treeview. The right panel is a representation of the data record for the
selected node in the tree view. The right panel is dynamic, that is it is
constructed on the fly at run time as the users have the ability to define what
fields they wish to show and what the labels are for those fields.
I need the right panel to change the treeview node text when the record in the
right panel is posted. The general consensus is that it'd best be done with a
callback, but I've never done one before. Can anyone give me a simple example of
how to do this?
Answer:
What you are describing is a Mediator Pattern. In essence, you set up a class which
is aware of your two (or more) components. Set up properties to record changes and
then in the appropriate event handler, simply assign the new values. The Mediator
is solely responsible for synchonizing the two.
Very simple example (yours will be slightly more complex, but surprisingly probably
won't have too much more code):
1 2 TEditBoxMediator = class3 private4 FIsChanging: boolean;
5 FFirstBox: TEdit;
6 FSecondBox: TEdit;
7 function GetText: string;
8 procedure SetText(Value: string);
9 public10 property Text: stringread GetText write SetText;
11 constructor Create(const FirstBox, SecondBox: TEdit);
12 end;
13 14 constructor TEditBoxMediator.Create(const FirstBox, SecondBox: TEdit);
15 begin16 inherited Create;
17 FFirstBox := FirstBox;
18 FSecondBox := SecondBox;
19 FIsChanging := False;
20 end;
21 22 function TEditBoxMediator.GetText: string;
23 begin24 Result := FFirstBox.Text;
25 end;
26 27 procedure TEditBoxMediator.SetText(Value: string);
28 begin29 if FIsChanging then30 Exit;
31 FIsChanging := True;
32 if FFirstBox.Text <> Value then33 FFirstBox.Text := Value;
34 if FSecondBox.Text <> Value then35 FSecondBox.Text := Value;
36 FIsChanging := False;
37 end;
38 39 procedure TForm1.Create {...}40 begin41 FEditBoxMediator := TEditBoxMediator.Create(Edit1, Edit2);
42 end;
43 44 procedure TForm1.Edit1Change(Sender: TObject);
45 begin46 FEditBoxMediator.Text := Edit1.Text;
47 end;
and so on.
The idea is that the mediator handles the changes (and uses the internal flag to
prevent an endless
loop).