Randomblue
Randomblue

Reputation: 116273

Should views keep track of their model?

This nice article recommends against keeping track of the views belonging to a model inside the model. What about the opposite? It is recommended for views to keep track of the model(s) they are based on?

It seems difficult to imagine to do without. Maybe the recommended way is to use events, or something?

Upvotes: 3

Views: 201

Answers (2)

Andreas Köberle
Andreas Köberle

Reputation: 110892

Most of the time the view should know its model cause he is the visualization of the model. So the model can be there without a view, but a view without a model doesn't make much sense.

But as always there are cases where the view should not know its model directly. Think about a basket where a user can add products and maybe he can configure that products. You have different views that visualize the model, like a table with the products, a basket ico with the count of products and a view to show the total amount. All share the same model. So when ever the user creates a new model cause he delete the old one or order something and there after something new, you have to create a new model and pass it to your views. Sure you can to this by fire an event. But you can also pass a proxy for your model to your views, so the views always comunicate with your proxy and they never know that sometimes a new model was created.

Upvotes: 0

Chris Biscardi
Chris Biscardi

Reputation: 3153

Views always keep a reference to the model. It is accessible through myView.model or myView.collection.models.

Due to the nature of views, I cannot imagine a case where you would want the view to not know about the model. Event binding happens in the view with a reference to a model. (Think about the collection.add event. Wouldn't be possible if you didn't bind to a reference to the collection)

Upvotes: 6

Related Questions