3

Consider that you have some graphical interface that represents some data structure. For example a text field:

image description

This field is connected to the data structure through events. I tried to make diagram of this:

image description

Of course, there may be many GUI element and the structure can be complex. What happens is, that when GUI values are changed by user, the structure is updated. When the structure is changed from other source, it notifies GUI of the change.

What do I do to prevent this connections from looping? I thought of having some "silent" setter functions, but this looks dirty. What should the model correctly look like?

  • One common technique is to NOT update the change event origin (cycling a change back in to – Kristian H Oct 15 '16 at 12:25
3

One way to achieve what you're asking with minimal code changes is to check in both the view and the model if data has actually changed when a notification comes in before performing an update/notify.

Program-flow example:

  1. User sets text field to "Some text".
  2. GUI sends an update notification to the model with the new value.
  3. Model checks that the value has actually changed, sets the new value and then sends an update notification which is picked up by the GUI.
  4. GUI checks if the value coming from the model is different to the one it has, finds that it's the same and so does not perform an update/notify.

Code example:

if(newData != data)
{
    data = newData;
    notify(data);
}

The problem with having a silent setter is that there might be other components of your application that need to know when the model has changed but won't be notified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.