In MVC, why should the model notify the views, and

2019-08-01 09:08发布

问题:

In my world, the model notifies only the controllers subscribed to the model's event. Then the controller tells the view what to do, for example adding a new row to a list.

The same with the view: the view notifies the controller subscribed to the view's event. Then the controller modifies the model as needed, for example setting the name of a person, and call the Save() method on the model.

Okay, I know I'm wrong, I don't think every article about MVC is wrong because I'm thinking in another way. The point in MVC is to seperate the UI from the data model. How does this come true when the view and the model reach each other? Why should they do so?

Thanks for Your answer!

回答1:

Model-View-Controller is seen different ways by many people, but I like to think of it as a combination of several other patterns rather than as a single pattern. This may come originally from this note

The connection of the view to the model is an Observer Pattern, with the model notifying the view when it has changed. There's no need for the controller to be involved in this.



回答2:

I completely agree with you on this one.

For every project i work on, i try to enforce this:

View --> Controller --> Model

So that every action or event in the view call a specific controller method. This controller method will do his job (validate, call other service, etc) then if persistence is needed, it will the call the associated ModelService to persist the data.

in my world, a view component should never call a ModelService without going thru a controller.

But that's just me ;-) (and almost 100% of the good architect and designers i worked with)



回答3:

I like to think of the model as a transparent thing, adhering to some sort of scheme. Very easy to "read" by a view. I never make my views programmatic, in the sense that you can call all sorts of methods on it. Usually my view is HTML, my model has methods but is also capable of presenting itself as a plain data structure, and there is an intermediate: in the form of a template engine.

But, there are lots of variants for MVC. I don't think there are 2 developers who would exactly, exactly, agree on what MVC actually is. MVC is -in my view - a pattern to help you. It is not a law that is trying to hold your creativity back by exactly defining up to the last bit what you have to do.