Friday, February 21, 2014

Client-side MVC with JavaScript

Continuing the JavaScript theme from my previous two posts, there was one more JavaScript idea I wanted to investigate. I have to admit, I have been confused by what I've seen in the MVC space recently. It did not match up with what I thought of when I thought of MVC. Now, I'm not a web developer, this is not a topic that concerns me on a regular basis, but I feel like any self-respecting developer should have an understanding of these sorts of things.

Reading the Model-view-controller Wikipedia article actually made a light bulb go on in my head. See, I was stuck in the past and was thinking of all three components living on the server, but as client-side technologies have matured (read AJAX) the components have shifted to the client. This makes a lot of sense as MVC does not prescribe the exact implementation, rather MVC is a design pattern.


Whether it's client-side or server-side, you still have a controller that manipulates the model and a model that updates the view. With client-side MVC all three components would be written in JavaScript. With server-side MVC the model is a JavaBean, the view is a JSP, and the controller is a servlet. The latter is how I originally learned MVC and it is shown in the image below:


So what I decided to do was create a pure JavaScript MVC example whose model talks to the Node.js app from my last blog. There appear to be many existing frameworks for this, but they all looked way overkill for such a simple example.

The HTML


It simply has a few forms to trigger the different CRUD operations.

The JavaScript


I think it seems strange I need to refer to so many HTML elements in my controller. I could initialize the controller with the IDs it needs. That would be better, the controller would be less coupled. I still wonder if I separated my components correctly though. Is there a better way?

It's Alive

I ran everything on my laptop and dropped these files into a "public" directory at the same location as my my Node.js app. They are served as static files and this conveniently eliminates cross domain AJAX issues since both are at localhost.

The result of clicking "List All Wines":



Testing (in theory)

In my first blog I talked about how to get started testing JavaScript, so naturally I wanted to see if those principles could be applied here. It seems like the model and the view (with minor refactoring) would be easily testable. The AJAX requests to my Node.js app could be mocked as I demonstrated. I would say those components turned out really well. The controller would require more effort. I would have to pass the controller a mock view and mock model, but it's definitely possible. I think this conclusion gives merit to the design even though this was a simple example. I like the way it separated the unrelated parts of my code.