Since I'm learning the MVC pattern, this might be a very naive question.

I know that when something happens on the view (e.g. user clicks a button), the view calls the controller which in turn updates the model (e.g. set a flag to true). However I can imagine some scenarios in which the model changes without user interaction: say a timer that, after N minutes, triggers a change somewhere on the data. The model has now changed: how to update the view accordingly?

有帮助吗?

解决方案

This depends on the life time of the view. For short-living views, it may be sufficient not to update the view at all. It may be soon enough to display the new model content the next time the view is recreated.

For long-living views, one can implement something like the publisher-subscribe pattern. This means, the view takes the role of a subscriber and registers itself at some separate place (like an event manager) to become informed about certain kind of model changes. The model, however, takes the role of a publisher and sends the according events to the event manager in case the data changes. So the view can reread the particular model data whenever it gets notified about a change.

It will also make a difference if the view offers just read-only functionality, or if it allows the user a functionality to change the model. In case of the latter, it might be a good idea to implement some collision strategy, to find out if the data originally displayed in the view was changed between the time it was loaded and the time when the update happens. For several use cases it can be fine to rely on such a test and update the view only when a collision occurs.

许可以下: CC-BY-SA归因
scroll top