Thursday, February 15, 2018

Model View Controller (MVC) Pattern with Java Script

The Controller (C) listens to event stream.  Here we use click event

Model (M) provide access to data source.

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

The Controller tells to View to do something with Model data.
The View knows nothing about the Model apart from it's interface
The Model knows nothing of the View and the Controller
The Controller knows about both the Model and the View
The Controller tells the View to do something with the data from the Model

You need to add form input elements and a button to experiment this code.

var M = {}, V = {}, C = {};

/* Controller Handles the Events */
/* Model Handles the Data */
/* View Handles the Display */

M = {
    data: {
        userName : "Ping Pong",
        userID : "440"
    setData : function(d){ = d.userName; = d.userID;
    getData : function(){
        return data;

//elements who will receive data
V = {
    userName : document.querySelector("#inputUserName"),
    userID : document.querySelector("#inputUserID"),
    update: function(M){
        this.userName.value =;
        this.userID.value =;

//Controller handles all
C = {
    model: M,
    view: V,
    handler: function(){

document.querySelector("#submitBtn").addEventListener("click", function(){;

No comments:

Post a Comment