Skip to content

Design Pattern: MVC

fahimc edited this page Mar 18, 2013 · 2 revisions

##Definition separation of user interface logic from business logic

##Creating a Model

var model = new Model();

###Setting Values

model.set("title","hello world");

##Creating a View

var View = function()
{
        // create a variable to store the DOM object reference
	this.div;
        // create a method we can call to build the DOM object
	this.build = function()
	{
                // create a DOM object and append it to the body
		this.div = document.createElement("div");
		document.body.appendChild(this.div);
		
	}
        // create a method to add content to the DOM object
	this.setTitle=function(value)
	{
		this.div.innerHTML += value+"<br>";
	}
};

##Creating a Controller

var Controller = function()
{
        // create variables to holder the model and controller
	this.model;
	this.view;
        // create a function to initialise the view
	this.init = function()
	{
                // build the view
		this.view.build();
		
                // create an event listener to fire when the document is clicked,
                // we will need to wrap the function to ensure 'this' refers to the Controller
                // create a variable to refer to the Controller
		var root= this;
		
                // create an event listener and wrap the callback method.
		Utensil.addListener(document,"click",function(event){root.onClick(event);});
	}
        // the click callback method
	this.onClick = function(event)
	{
                // get the title from the model.
		var title = this.model.get("title");
                // set the content in the view with the title on every click.
		this.view.setTitle(title);
	}
};

##Initiate the Classes

//create the model and set the title
var model = new Model();
model.set("title","hello world");

// create the view
var view = new View();
// create the controller and set the model and view
var controller = new Controller();
controller.model = model;
controller.view = view;
// initialise the controller
controller.init();

Clone this wiki locally