6.4. Model View Controller

Let’s critique our first prototype a bit.

Let’s fix this second problem right now. The way we are going to do this is to redesign our application to follow the Model View Controller paradigm. The MVC paradigm is a tried and tested way of making applications that gives you a nice separation of concerns and will solve the problem we identified in our critique. The following diagram gives you a good idea of what is going on.


We will divide our coding into three distinct blocks:

In the next revision of our program the controller will no longer directly manipulate the html that we see on the page but rather will manipulate our model. When a user clicks on the Add button the controller will create an Item and then call a method on our ShoppingList object to add the item to a list.

Here is the code for our new model:

'use strict';
class Item {
    constructor(name, quantity, priority, store, section, price) {
        this.name = name;
        this.quantity = quantity;
        this.priority = priority;
        this.store = store;
        this.section = section;
        this.price = price;

        this._purchased = false;



class ShoppingList {
    constructor() {
        this.newItems = []
        this.oldItems = [];

    addItem(it) {

Now, our controller should simply look like this:

var shoppingModel = new ShoppingList()

function clickedon() {
    let rowcolids = ['itemname', 'qty', 'store', 'category', 'price', 'priority']
    let vals = {}
    for (let cid of rowcolids) {
        vals[cid] = document.getElementById(cid).value;
    let it = new Item(vals.itemname, vals.qty, vals.priority, vals.store, vals.category, vals.price)

Now all the controller does is create a new item and add it to the list. Nice!

The remaining question is how does the Model let the View know that it has a new item and that new item should be added to the html table so our user can see it there? We will tackle that problem in the next couple of sections.

You have attempted of activities on this page