Sunday, August 7, 2011

Client Side Javascript MVC: Don't Hate On Controllers

Padraic Brady wrote a compelling article about the Model in an MVC framework.  I wholeheartedly agree with the point he makes - especially in the context of Server-Side code.  Spreading the business rules into the Controller or even the view in a web application is a very bad idea.  But, I don't think he explains "why" clearly enough. 

The MVC pattern as described by Trygve Reenskaug describes the View as the component that the user interacts with directly.  The view then interacts with the Controller as a way to abstract the complications of the Model with the complications of the View.  The bastardized MVC pattern us web developers are used to seeing is one in which the user interacts with the Controller which pushes some data into a static View and returns the results of combining those two things.  Since the View is static, and the Controller returns with an "all done" before the user even starts interacting with the view, the Controller has a nearly non-existent supporting role to play other than a data-pipe.  In client-side code, I see something far closer to the original MVC pattern described by Reenskaug.

In client-side code, I see the View as the full DOM tree (perceived as HTML/CSS). The Controller is a not-so-thin layer of Javascript that's aware of the complete DOM tree and the Model.  The Model is a separate not-so-thick layer of Javascript that doesn't ever query the DOM, but rather very well specified snippets of DOM such as a <form> or a backing object not part of the DOM given to it by the controller.  The Controller plays a larger role as the glue between a dynamic interface and the Model that backs that interface due to the fact that the View constantly changes as the user interacts with the application.

Back when Reenskaug was writing GUI applications in Smalltalk, he had similar concerns to deal with.  The Model, View, and Controller all had an important role to play.  While web developers have hijacked and mangled the term "MVC", don't let lessons learned there cloud your understanding of what a real Controller is.

No comments:

Post a Comment

AddThis

Bookmark and Share