JavaScript MVC

by Jonathan Snook

26 Reader Comments

Back to the Article
  1. In my experience MVC is a synonym for overflowing complexity. I found it’s more of a Monk thing (Adrian Monk) than a real helper in programming robust code.
    While with a direct hacker approach you need usually one piece of code, with the MVC pattern you need (at least) three. And even if it sounds very well to have logic and representation divided – it’s a self-deception.

    You will never ever achieve that goal because you can never represent something that didn’t pass your logic handlers.
    So each time you implement additional functionality you will need tons of “pattern”-code. Leading to more code, more complexity, more download-time, more interfacing, harder debugging…

    I don’t like it. I like the agile programming of small collaborating components (some of them actually meet the MVC concept…).

    Copy & paste the code below to embed this comment.
  2. Actually, this a very good article as it will introduce a lot of people to a very common programming acronym and concept and, like it or not websites are becoming more and more “programmable”.

    However, the articles does fail to raise the problems of client-side validation – if a user has Javascript disabled or the user is a “bot” then the validation will not occur. You always need server-side validation and trying to do this in Javascript is an invitation to disaster.

    What Javascript does very well is allow you to provide good user feedback in realtime – avoiding the problem of users filling out a whole form, pressing submit, waiting and then being told they’ve made some mistakes. Some of the work can be split between the browser and the server or Javascript can simply pass messages back and forth using AJAX (yuck), JSON (less yuck) and preferably SSE. Future extensions to HTML might allow browsers to implement some of this directly based on the metadata.

    Most web-frameworks now provide transparent generation of this kind of code so you don’t have to worry about it yourself but it’s a very good idea to have some understanding of what’s actually going on.

    @proxiss – loosely coupled components are certainly preferable but I’d rather have developers working with some standard programming model rather than hacking it every which way each time. More time is spent reading code than writing it.

    Copy & paste the code below to embed this comment.
  3. @proxiss: I hoped to temper the article with an understanding that it’s practical in more complex applications and, in my experience, has actually led to less code and greater simplification because of it. With some of the upcoming stuff I’ve been working on at Squarespace, for example, this pattern has come to good use as different models have to represented in different states, including config dialogs, in-document layout, etc. Adding new models to edit is a matter of editing one component, not three. I’ve had other projects, as well, that have come close but would have been easier to develop using a stricter MVC methodology. Instead, there was too much dependence between components, making it harder to work on as the application got more complex.

    @Charlie Clark: The section on Progressive Enhancement was meant to address the issue but admittedly, didn’t specifically mention server-side validation. Yes, it’s always important to perform these tasks on the server-side. “Never trust anything from the client.”

    Copy & paste the code below to embed this comment.
  4. @proxiss – As your program grows in size, you will be forced to consolidate common code fragments, or code maintenance will quickly become unmanageable. The only sane way to do that is to generalize your code so that it’s re-usable, and that is exactly what MVC accomplishes. But if your program is so small that you hardly have any common code fragments, then of course you shouldn’t use MVC.

    Copy & paste the code below to embed this comment.
  5. I’ve seen the term MVC pop up over the past few years, always wondering what’s so great about it. I have yet to find an answer. I’ve worked with a couple of systems that implement a MVC methodology and trying to troubleshoot or debug MVC code ends up taking far longer than doing the same with non-MVC code. One idea behind MVC is that a system should be designed to be able to accommodate a large variety of recurring patterns when in fact, they rarely recur. Maybe I haven’t worked with MVC enough, but from the experience that I have had with it, MVC ends up creating so much obfuscation that it becomes totally unwieldy. The time it takes to develop a robust MVC far outweighs the benefits, as the time required to maintain and debug it will trump any times it saves in writing code that uses the MVC. I agree with virtually all of what proxiss wrote earlier.

    To me the real issue, or problem, lies in the fact that we’re forcing people to create MVC patterns to account for shortcomings in whatever language it is that they’re using. In other words, why should we have to develop such complex structures to account for patterns that have become so commonplace? Validating email? Any language by now that is used on the web should have this built-in. Using JavaScript as an example, why after nearly 15 years of existence does it not inherently do something as simple as email validation? The problem exists in the language itself not keeping pace with demand; therefore we have to come up with workarounds until it does so.

    I consider objects, functions, methods, etc. all ways to reuse code quite easily. I say the problem is that the tools we are using are not updated as often as they should be which forces us to come up with these workarounds. Elegance lies in simplicity. While MVC may have its place, I’m sure we’ll look back at some point and question what were we thinking. JavaScript is popular because it is dead simple to use, not because it can be bent into a framework.

    Copy & paste the code below to embed this comment.
  6. @catchmyfame – What you’re really arguing for is a library to handle all your commonplace patterns, such as jQuery or Dojo. A programming language itself has no place in dealing with ever-changing specifications for things like input validation. Imagine having to update your JavaScript engine every time one of the many RFC specifications change, when you could simply link to an updated library.

    Try implementing a Content Management System sometime, or design a website with hundreds of dynamic pages, and you’ll see where MVC really shines. But if you don’t have the complexity to warrant it, then don’t use MVC. It’s as simple as that.

    Copy & paste the code below to embed this comment.
  7. Geoffrey, I did in fact just recently implement a CMS which uses a MVC and it was a nightmare to troubleshoot. Also, how often do RFC specs change? Not often. I hardly think that something as essential as email validation is too much to ask to have in a language like JavaScript.

    Copy & paste the code below to embed this comment.
  8. I agree with catchmyfame. Why bother with generalization on every single subject. I.e. PHP was encouraged enough to pack the http-post mechanism into the core engine (_POST array) – and PHP has i.e. a simple “mail()” call that does what you expect.
    Seems they are not afraid of RFC changes…

    On the other hand, Geoffrey, you have generalized libraries that may handle every – never needed – use case for you (like javax and javamail), but force you to write tons of code (and xml configurations) for the one simple appliance you need in 99% of all cases.

    I also agree with Geofffrey – choose your tool carefully, and choose a tool that’s not too much generalized.

    We’re wasting too much time with foreseeing things that never eventuate.

    Copy & paste the code below to embed this comment.
  9. I think, the idea is very good, but in most cases the usage of a MVC principle is just an overdose of script (except in large scaled projects).

    I really like the way, code is seperated in its logic functions, but in the case of JavaScript, there are better ways. I mean writing some pieces of generalized code, that give me the amount of flexibility can have nearly the same result, without making the issue that complex. (I aggree – in very large project there may be a point, you can think about the usage of a JSMVC.)

    Thank you for the article. Good work.

    Copy & paste the code below to embed this comment.
  10. John Resig should be mentioned somewhere in the article considering that his work alone likely accounts for 50% of the revolution in JavaScript we’ve been seeing in the last 2 years. I messed with other frameworks and, like everybody else, came to jQuery like, “Oh my god. I can’t believe it”. Without jQuery (and some help from Prototype) JavaScript wouldn’t exist anymore.

    Copy & paste the code below to embed this comment.
  11. I like the idea of creating HTML templates in JS and replacing using regexp. In fact a lot of JS frameworks have this functionality built-in (see String.substitute() in Mootools for example). However you’re still mixing concerns. Much better in these cases – IMO – to keep most of this logic in the controller… of the web server. This keeps your views in HTML for the designers, and you’d just use AJAH to pull the rendered views in to the client. Also helps to avoid duplicating logic in the client/server. In your example JS would validate the form on the server and the server would return the HTML chunk of errors – if any. I think much more useful than MVC for JS is event delegation – a different kind of abstraction that also helps with development and maintenance in the long term.

    Copy & paste the code below to embed this comment.
  12. @rloaderro: HTML generation should be done in the view, whether it’s on the server or client. The controller in an MVC architecture should act as a mediator. I tend to take a couple approaches to HTML generation depending on the project. If there are a variety of ways that the HTML may get generated, such as within a CMS with multiple object types, then rendering on the server is (I find) easier to maintain. However, in apps that have a more singular focus (like a calendar), including an HTML template within the page, such as in a JS-embedded template, works well and usually means less data having to be sent down the pipe.

    As to others who feel this is overkill, it can be. But it also doesn’t have to be. Here’s an example: you’re using jQuery UI to provide sliders for a mortgage calculator. The UI components are your view. The event management is your controller. The question, then, is whether you need a dedicated object for your model. If this was all the page was doing, then not likely; event management and data management would be combined into a single function and that’s okay. If the calculator was part of a larger app such as a budget estimator that needs to save income and expenses to a server, then it makes sense to combine entries into a model that can save values to the server while the event delegation continues to remain simple. How much more complex have I made the application over just the calculator? One object. Is that overkill? I don’t think so.

    Copy & paste the code below to embed this comment.
  13. I’m disappointed by the responses to this post from the Javascript and HTML developers out there.  This kind of framework is exactly what JS needs.

    I had the same initial reaction when applying MVC design patterns to Adobe Flex a few years ago.  I thought it was introducing a level of verbosity and complexity that not only made development slower, but actually ran slower as well.  But, in the end, the goal wasn’t small and fast code.  It was manageable code.  And in any medium-to-large project, IMO, manageable is many times more important than small-and-fast.

    I’m picking up Ruby on Rails now as well and I’m even more convinced that MVC is the right way to go for front-end web development.

    1.  Project Size
    Everyone is correct that you can build a small project without using a framework – just like you can build a bookshelf or fix a broken pipe without going by the book.  But just because you can doesn’t mean you should.  And as web development professionals we should be advocating the correct way to do the job, not the “good enough” way.  That means not only frameworks, but testing and documentation as well.

    If you’re a small web development shop who builds one-off projects for clients, you probably don’t need a framework.  Every new project begins from scratch with a few utilities and snippets you find useful.  But in my experience I’ve always had to maintain a site or web application over many months and years.  And I’ve had to hand that project off to other developers to maintain even longer than that.  If you’re in that line of work, you need to do things right, even if the project initially seems small, because things always change.

    In fact, I wouldn’t even want to work with a small shop that didn’t use some kind of framework, even if it was just homebrew, because that would not only demonstrate a lack of professionalism in their craft, but also a sense that they’re not learning from their experience to build future projects more efficiently.

    2.  “Overflowing complexity”
    I think it’s a common mistake for people to confuse verbosity with complexity.  MVC is actually a lot simpler than most of the homegrown complexity management systems I’ve seen used with HTML/JS code.

    From a bug report, I can usually tell whether or not the issue lies in the model, view, or controller, and I structure my filesystem in such a way to make it easy to find these files.  And everyone else who comes along after me, once they understand the framework, knows where things are supposed to be.  (In RoR, it’s called “convention over configuration”)

    In my experience with the “direct hacker approach”, I find myself and others constantly searching through a flat file system, grepping through folders full of .js files looking for the function name or variable that is supposed to be used in some context.  And once a bug is found, everyone has their own special way of fixing it, which may solve the immediate bug, but may also have some unwanted side effects which are hard to track down because the relationship between different .js files isn’t explicit, either by naming convention, folder structure, or any of the other things a framework provides.

    But, I’ll admit, there is something annoying about the verbosity of frameworks.  You do end up with a lot of template code that doesn’t do much, bloats your code base, and may make your site slower.  But I find template code to be more manageable.  It’s like carving little expansion slots into your code for that next big feature request.  Everyone can agree on where to start, instead of everyone carving out their own slots wherever they like after the feature request is made.  Seeing empty slots also makes it easier to see where code may be lacking in things like validation, security, or visual design.  Finally, it makes it easy to scope tasks knowing that I don’t have to reinvent any constructs to deal with a feature request.  I can just say “I can do that, and I know exactly where to start, and it will take me 1 hour to complete”.  That’s valuable if you’re working with an agile team.

    Once you’ve decided that you’ve made the correct architecture decision, verbosity is just something you manage.  Most people use code generation to create templates so the only thing they have to write is the customization.  But the best approach is abstraction.  Assembly was powerful, but it was verbose, so we built languages on top of it to abstract away the verbosity and complexity and just deal with the stuff that matters.  Ruby is a excellent case study in this overall.  jQuery and prototype do this well for JS.  But RJS in Rails, Google Web Toolkit, and Objective-J are the places I’ve been looking to for abstractions that will make MVC design patterns in JS less onerous.

    Copy & paste the code below to embed this comment.
  14. I have to say that I totally agree with eddroid on this one. Following a pattern will lead to more maintainable code in most cases, and the MVC pattern is a well known pattern that many developers know how to use already. You don’t even need a framework for this, as long as you are following the pattern it will help you out a lot.

    We are used to patterns on the server side, and with todays javascript heavy pages, why should we not use one on the client side as well? We all know how easily javascript can get out of hand and become a mess.

    Thanks for a great article.

    Copy & paste the code below to embed this comment.
  15. Jonathan, your article was spot on about having an MVC framework in JavaScript. However, I have to disagree with your decision to put your validation code inside of the Model class instead of the Controller. In your example, the data validation is very simple and only deals with the format of the data, but in many cases data validation includes much more than just format checking, and can include specific business logic and view settings which all belong in the Controller not the Model.

    For example, in your calendar scenario if you accepted date inputs, the validate code would be much more complex. What if you wanted to define business logic that said they could not enter dates on a Sunday? Or what if the View had a checkbox that said “Exclude Holidays”? Or what if you had to make an AJAX call to verify that you didn’t have a meeting on that date?  As you can see, validation code is much more than just “format checking” and can get quite complex and may require business rules. Thus instead of putting some validation in the Model and some in the Controller, make it consistent and maintainable and put it all in the Controller.

    My 2 cents.

    Copy & paste the code below to embed this comment.
  16. I think the problem with evangelizing MVC is that it only seems useful in very large, very complex projects. Most of those projects usually contain code that the developer/business would prefer to keep very close to the vest.

    I notice that this article did not even contain a working demo.

    Are there any open-source, non-minified MVC projects available to be used as good examples of MVC method and its usefulness?

    Copy & paste the code below to embed this comment.
  17. Here’s a demo for you: go to applebox.com.au .. hit the browse DVDs button. The app is run as a completely in-browser JavaScript MVC with a controller that manages multiple iframes (as views) and switches the z-Order to display the current ui. This is closer to a typical server-based MVC product where page flow is managed server-side .. EXCEPT the page flow is managed in-browser.

    To my mind the article provides an MVC model that is an example of widget-based data visualisation/control, rather than a more typical page-based visualisation that most web apps exist as today (note this includes Single Page Apps where there’s plenty of widgets and AJAX hijinks .. but which ultimately must face the issue of navigating to another page/SPA once the full capability of a given page/ui is explored).

    The article is great .. but it doesn’t point out the huge advantage of going MVC in the browser .. and that is maintaining state client side, and reducing the server to only needing to serve stateless data. With APPLEBOX, once a UI/View is realised, it maintains it’s state and is shuffled back out of view (in the iframe stack) until it is needed again. When the controller needs to return to it .. it bring it forward and the ui then retrieves whatever data it needs. This means no reloading of extensive js libs and ui widgets per page navigation.

    APPLEBOX is 2 years old now, and the architecture is rock solid. Whilst its great to see frameworks such as sproutcore, JavaScriptMVC and others out there, I’d like to see dojo/jquery/yui/ext to step up into this new area, and provide some application controls (starting with mvc) rather than simplying being widget or javascript foundation toolkits.

    Copy & paste the code below to embed this comment.
  18. I agree with the post above: if the likes of jQuery and Mootools start encouraging people to write mvc javascript, everybody will use it.
    That is the only way!

    Copy & paste the code below to embed this comment.
  19. Jonathan is right, for smaller applications it is not always worth it to type so much code. But now, the (increasingly used) frameworks make it easier to write JavaScript MVC—so I also think this could accelerate the spread of MVC.

    Copy & paste the code below to embed this comment.
  20. MVC designed systems are great, but they have become all the rage in good ways and bad.  I’ve come across quite a few projects that have way too much code in creating a proper MVC (for future development maybe?), only to have the system do something that could easily be done with a fraction of the code, yet still be completely usable for other programmers who stumble across the code.  So in mu opinion, K.I.S.S., unless you know you’ll be expanding the project to a decent size in the future.

    Copy & paste the code below to embed this comment.
  21. I’m glad you are publishing more technical articles and less fluffy ones. Still not convinced MVC is the way to go for Javascript RIA.

    It would be nice if one could port some an Actionscript framework (PureMVC springs to mind) to Javascript, but I doubt that would be worth it, or even feasible.

    Copy & paste the code below to embed this comment.
  22. Interesting article, I wasn’t aware of people trying to implement MVC into front-end code. I’d guess it’s coming from the .net boys trying to cope with javascritped business logic.

    I’m not sure what you’ve described is actually MVC. You’re mixing templates into the javascript and using AJAX to pull data. Also, there’s that whole issue of application behaviour code supplying business logic to the entire application through things like validation routines. It’s the job of the back-end controller to define relationships not the ‘view’ behaviour code.

    A much better approach would be to add the elements <div id=“database” ></div id=“templates” ></div> and have your behaviour logic read the content of those elements to control client event handling. Let’s look at an example you describe concerning the preloading of a calendar. You load your special event days into the ‘database’ as a table for those months prior and ahead of what is displayed. You might call this client-side database normalisation. Your controller can then read the recieve the next click event, the model can retrieve the special event days and the view fetches and builds the template which is inserted as a widget by the controller.

    For brevity. This is more like what the setup of MVC validation messages, as you’ve described, should look like on the page:

    </div id=“templates” >
    <h2>{varMessageTitle}</h2>
    <ul>
    {loop varMessageData as Data}
    <li>{varData}</li>
    </ul>
    </div>

    </div id=“database” >
    <table name=“error_messages”>
    <tr>
    <th>id</th><th>message</th><th>classes</th>
    <tr>
    <tr>
    <td>1</td><td>Your email address is invalid</td><td>warning required</td>
    <tr>
    </table

    <table name=“validation_requirements”>
    <tr>
    <th>id</th><th>name</th><th>requires</th>
    <tr>
    <tr>
    <td>1</td><td>email_address</td><td>has_email_checkbox</td>
    <tr>
    </table>
    </div>

    In any event I still think that MVC for web application development is a collective madness which we’ll all look back on in ten years time and have a good laugh. MVC doesn’t clearly define ORM as an inherant part of the pattern, which, makes CMS development obtuse at best.

    Copy & paste the code below to embed this comment.
  23. @waffle: doing view rendering on the server is definitely a valid approach. However, the tradeoff for me is how much time/bandwidth do you sacrifice in doing so. If you’re rendering a complete calendar of events for each month, it’s almost pointless to do it via Ajax—especially if there aren’t any events within a particular month. I prefer pulling in just a JSON request because it’s smaller. Storing that information client side then becomes part of the model (essentially, keeping track of state and syncing with the server).

    Are we going to look back to server development 10 years from now and all laugh about having used MVC? With the increasing complexity of client-side apps (not only on the web but also in desktop apps like AIR and Titanium), it seems like a natural choice.

    Copy & paste the code below to embed this comment.
  24. I tend to agree with Eddroid. MVC isn’t new and the fact that it has survived decades for many similar discussions such as this to be taking place today gives everyone something to think about, especially its detractors.

    Even if I’m doing a small dirty project, I still find more merits doing it right. MVC patterns for smaller projects isn’t going to give you that much more overhead in any case. Backtracking your codes a year later won’t make much of a difference in a small project whether its done with MVC or not. But it does make a difference when you are working with a team. Your project may need to spin off to something larger, or open-source, etc from the same code base. Then I’d think your MVC foundation would do you justice.

    I’d rather not be caught realizing this a year later into development.

    Essentially, I look at the quest of applying MVC patterns for javascript/ajax more than just for goodness’ sake, but a case of developing healthy coding habits, seeing and thinking right. A cause with more benefits than not, most certainly.

    On the server side, I like codeigniter for its loosely coupled design which gives developers more flexibility. I could stray from convention where necessary. Likewise, I think in browser MVC, we should also find that balance.

    It isn’t too difficult to consume a fish without swallowing its bones. Great article Jonathan!

    Copy & paste the code below to embed this comment.
  25. There are other patterns to separate concerns. MVP, Humble Dialog, and even Presenter First.

    For me the separation helps because I test first then write my code. When I need to refactor, adding new behavior to my app, separation is what I need.

    Use of JavaScript is to give a more responsive experience the user. An example of this would be if you wanted to display some markers on a google map. The addresses are stored on your server. The addresses have no geocoding. User requests data from server. Client requests geocoding from a geocoding service. Display markers on google map. The other way would be my server having to request geocoding. then sending data to client.

    OBTW why not have the address be behind somebody else’s API. So now all my server has to serve up is HTM, JavaScript, and CSS. Let the client pay for the bandwidth.

    Now my business costs go way down. My programmers (me) don’t have to invest in backend software maintenance costs. Learning PHP, Python, Ruby, DOTNET, only so far as needing to know how to get a server up and running.

    Hmmm…. wonder if you could write a mongrel-like server in JavaScript. Just embed SpiderMonkey.

    Copy & paste the code below to embed this comment.
  26. MVC was first put in practice in the development of the Smalltalk GUI. The latest work by the same team is the Squeak language and environment. Squeak has a GUI toolkit named Morphic which is not strictly MVC because after 30 years of trying they concluded it is just not worthwhile to separate the view from the controller, as the two are naturally very interdepedent. So for GUIs and client-side web programming the way to go is M/VC: split the model from the rest, and be happy.

    Copy & paste the code below to embed this comment.