IT_Layman
IT_Layman

Reputation: 347

The Model-to-View communication in MVC?

I'm learning MVC now and I just got that when the model is modified by the controller, it can notify the view to update the data from model. While I'm quite confused about it. Since the model is modified by the controller rather than itself or something else, it should be the controller that sends the update notification to the view. Also I haven't found any example of such Model-to-View communication, please give me one to make it clear if anyone understands this idea well.

Upvotes: 3

Views: 2130

Answers (2)

Fuhrmanator
Fuhrmanator

Reputation: 12882

Model to view communication is often accomplished via the Observer pattern. The code in views tends to change more than the code in models, so Model-View separation means the model elements don't depend directly on the view elements. You can add or change view code and the model code is not affected.

A model element whose state changes just notifies all its observers. The state change can happen because of a controller, or because of other reasons (values change over time).

See https://msdn.microsoft.com/en-us/library/ff649643.aspx in particular the following:


(source: s-msft.com)

Upvotes: 1

iluwatar
iluwatar

Reputation: 1803

The central component of MVC, the model, captures the behavior of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application. A view can be any output representation of information, such as a chart or a diagram. The third part, the controller, accepts input and converts it to commands for the model or view.

Typically the controller receives user input such as key presses and mouse clicks and based on that modifies the model. When the model changes the view needs to be updated to reflect the changes.

There are a couple of options how to implement the view updating.

A) The view update can be implemented by calling it directly from the controller after it has modified the model. For an example, see here.

B) The view update can be implemented using the Observer pattern. In this case the model fires update events on the view each time there is a relevant change in the model. For an example see here.

Upvotes: 1

Related Questions