MGM discussion
Home Up

 

 

A MGM Pattern question.

Khanh Cao kacao@msn.com writes:

Hi Andy,
I've read your article about the MGM Patterns, it's a great pattern.
However, I have a question, could you please show me.

Let say I have a Textbox (GUI), a business object with only 1 property Text,
a mediator-view as your pattern defined.

When changing Business.Text, this procedure is called:

procedure setText(Value: String);
begin
  FText := Value;
  NotifyChanges; // notify mediator to change Editbox content
end;

therefore, mediator is notified:

procedure BusinessChanged;
begin
  FGUI.Text := FBusiness.Text; // this makes Editbox OnChange fires
end;

OnChange event of Editbox:

procedure Edit1Change();
begin
  Mediator := FindMediator(Self)
  Mediator.Business.Text := TEdit(Self).Text;
  { This line would call Business.setText and make an infinity loop }
end;

The only method I've thought of is let the Mediator modify FText field of
Business object. But in this way, Busniess and Mediator have to be in a same
unit. Is there another way to solve this problem?

Thanks for your sharing!
Karr. C.

ANDY'S REPONSE

 Thanks for your interest in the MGM pattern.
 Your assumption in the above code is that the Editbox OnChange fires
 when you programatically set the FGUI.Text, which would cause

  gui changes -> mgm notified -> changes model ->
                 model notifies mgm -> mgm modifies gui -> gui changes

  and so on, infinitely!!   See your highlighted lines above.

  However the Editbox OnChange fires only seems to fire when the text is
  altered by the user in the gui.  It does not fire when the edit1.text
  is changed programatically.
  So there is no loop.

  I tried it in Delphi 6.
  Here  is a sample delphi app that proves it.  It has a cheaper form
  of mgm which I just whipped up, in order to demonstrate the point.

  Hope this helps.
  -Andy Bulka

  P.S. If the event HAD fired, you could

    1. temporarily disable the event by rewiring the event handler to Nil
       before writing to it programatically, then restoring the event handler
       again (yuk, but possible. You often have to do this when using mgm
       with treeviews.)
    2. provide a way of setting the model data which does not trigger a
       notification.  Make the private data public.  Again, yuk.

    ... anyway thankfully you don't need to do either of these things
    since Editbox OnChange does not fire when the edit1.text
    is changed programatically

Further comments? email me