"Hello World" in MVC Pattern

hrishikeshp19 picture hrishikeshp19 · Dec 14, 2011 · Viewed 33.4k times · Source

In an interview for some company, I was asked this question.

What design patterns do you know...then I was told to write simplest "hello world" application based on MVC Design Pattern.

I came up with a JavaScript program

var arr = ["a","b","c","d"];   // this is an array, same as store or model
alert(arr[0]);                // this is controller
//and browser alert is a view.

later I was told that alert is a view. The basic concept about MVC I know is any changes in Model are reported to View. And there is a controller in between to call the methods.

Can you correct my approach, or come up with an alternate solution for hello world MVC application. Also explain subtle aspects of MVC.

Thanks.

Answer

Raynos picture Raynos · Dec 14, 2011
var M = {}, V = {}, C = {};

M.data = "hello world";

V.render = function (M) { alert(M.data); }

C.handleOnload = function () { V.render(M); }

window.onload = C.handleOnLoad;

Controller (C) listens on some kind of interaction/event stream. In this case it's the page's loading event.

Model (M) is an abstraction of a data source.

View (V) knows how to render data from the Model.

The Controller tells to View to do something with something from the Model.

In this example

  • the View knows nothing about the Model apart from it implements some interface
  • the Model knows nothing of the View and the Controller
  • the Controller knows about both the Model and the View and tells the View to go do something with the data from the Model.

Note the above example is a severe simplification for demonstrating purposes. For real "hello world" examples in the JS MVC world go take a look at todoMVC