Saturday, September 24, 2011

3 steps to MVC in JavaScript


  1. Read this article MVC Architecture for JavaScript Applications by Peter Michaux. It's a must-read and it nicely explains how the observer pattern works in the classic MVC. (Keep in mind that the MVC that you know from Rails/Django is a limited MVC, that's a topic for another post).
  2. Use Backbone and Underscore to handle events or roll your own observer mechanism (as described in Peter's article).
  3. (optional) Use CoffeeScript to make your code prettier.
Let me quote Peter Michaux:

In a nutshell the classic MVC architecture work like this. There is a model that is at the heart of the whole thing. If the model changes, it notifies its observers that a change occurred. The view is the stuff you can see and the view observes the model. When the view is notified that the model has changed, the view changes its appearance. The user can interact with the view (e.g. clicking stuff) but the view doesn’t know what to do. So the view tells the controller what the user did and assumes the controller knows what to do. The controller appropriately changes the model. And around and around it goes.

In the GameBoxed platform, we have a Monopoly-like Facebook game. There's a concept of a player (this is the model). A player, after rolling a dice, can receive points and when he does we need to update the player-details box.



When the page is loaded (our games are one-page apps, no full reloads), the Monopoly object is initialized. It's a facade object responsible for initializing models, views and controllers and wiring them together.

At some point thanks to some users actions the player.addPoints method is called which triggers the "player:updated" event with some arguments. Thanks to the controller (the bind method), the PlayerView object is notified that something interesting happened and the view updates the html (with some jquery helpers).

This pattern is very useful and can be used in most of the typical UI scenarios. Let me know what you think about it.
 If you read this far you should Follow andrzejkrzywda on Twitter and subscribe to my RSS.

3 comments:

tbeseda said...

I really like this set up. It's working well for my single page apps. One question, where do you handle user input? That is, where do you attach even bindings for interactions like updating a form or a click?

Zorro said...

I see how this works and it looks neat. On the other hand, with this setup the V and the M are tightly coupled, and the C is really transparent!

This is an MVC like this:
--change: DB <- M <- C <- V <- User
--show: DB -> M -> V -> User

I think it's not worth it to have a transparent C when showing content to the user.

bootz15 said...

I think a little initiation code would be helpful, too. How do you instantiate each object?