Should a Controller access a view's model directly?

211 Views Asked by At

I am in doubt with the usage of MVC in context to the example as follows :

Consider an example of a little drawing application.

  1. Now say for example, there is a textbox where user can enter ANGLE for selected shape, Expected result should be, that each selected shape should get rotated as per the angle specified in textbox.

  2. Say I have a shape object that is a View named as ShapeView The given view has its own data like its position, current angle of rotation , stroke color, fill color, etc... So I have a model for the shape as ShapeModel

  3. So now I have Controller, that handles this textbox and the multiple shape views. A change in textbox value lets controller take necessary steps to rotate the shape.

QUESTION:

So the doubt is , should the controller directly access the shapeview's shapeModel and call the rotate method? OR should the Controller call shapeView's rotate method, that internally calls shapeModel's rotate method?

In short, should any outside entity access a view's model directly? Or should it go through View only? Is it a good idea to access model directly? Any issues or concerns if I access so.?

1

There are 1 best solutions below

3
On

The view in Backbone is behaving as a controller.

E.g.

  ShapeView = Backbone.View.extend
    el: "input#angle"
    events: 
      "onkeypress" : "update_angle"
    update_angle: (ev)->
      angle = $(ev.target).val()
      @rotate(angle)

Most of time you don't need additional controller for the same view. The ShapeView controller can handle everything on its own. It's in charge of the views it's created for. If you need access other view controller or model, you can hook them on a global namespace, e.g. App = App || {}

If you have many values and those values needs to be accessed from other controller, you can create a Shape model, that model should not be kept within the View Controller, instead you should bind it to global namespace and set its attributes through global namespace.

You also can bind event on the model like this

shapeView = new ShapeView
shape = new Shape
shapeView.listenTo shape, "change:angle", shapeView.update_angle

This way, you can have multiple controller, listening to the same data model and get views updated accordingly.

Model and View controllers should be decoupled as much as you can.