JS MVC Test

This document is intended to demonstrate an implementation of MVC (Model, View, Controller) separation in Javascript OOP. (Or more accurately, the Observer design pattern, since this example merges the view and controller into a single class in one instance.)

In this example, ShoppingCart is a class (defined in Shopping.js) that inherits from the MVCModel class (defined in MVC.js). The object knows only its data, and nothing about presentation. It only knows that any views which have 'attached' themselves to it should have a method named 'updateView' called when the data changes.

ShoppingCart_Summary is a class that inherits from MVCView, which is one representation of the view of the shopping cart. (Seen at the top of this page.) It contains the HTML and DOM methods needed to create the div and update the total number of items.

ShoppingCart_Details is another class that inherits from MVCView, and is the full shopping cart listing that appears below. As a controller, it can modify the ShoppingCart (when you change item quantity); doing so causes the ShoppingCart model to update all viewers on the page, without having to know who they are or how they operate. This benefit of MVC type separation allows multiple views to be instantiated at once, and to be changed independantly of changes to the model (assuming the data-accessing and changing interfaces of the model class remain the same).

This document is not intended to show a stunning display of either coding style or JS packaging. For example, the ShoppingCart_Details class does a very naïve update strategy, deleting every item row and then rebuilding it from scratch every time updateView is called.