See http://www.webessence.nl/lab/mvc/ for an example of a MVC architecture for a Javascript app. There are 3 views connected to the model.
The cons of the MVC is it is abstract en has overhead, so in simple applications, it is too much.
The pros are experienced when you have a large application, where there is a alot of synchronization to do. In the example above, I have 3 views of the same "Customer" model. If a customer is selected, the views are notified by the model and can update their own user interface. This way the application doesn't get more complicated if you add more views (widgets) to it.
There are many ways to implement a MVC model, but I use the following idea:
var Model = function() {
// Properties, like:
this.selectedCustomer = null;
this.customers = [];
// Events, for example:
this.selectedCustomerChanged = new ModelEvent();
// For implementation of ModelEvent, see example source.
};
// The view gets the model and optional a controller.
var View1 = function(model, controller) {
this.model = model;
this.controller = controller || new Controller(model);
// Build up the user interface for this view, for example a select list of customers:
var select = document.createElement("select");
// TODO: add customers as options (not shown here)...
// When the user selects a customer, call the controller:
select.onchange = function() {
var id = select.options[select.selectedIndex].value;
controller.onSelectedCustomerChanged(id);
};
// The view listens for events of the model, and will update it's user interface.
this.model.selectedCustomerChanged.attach(function() {
// Update your user interface, because the model says
// the selected customer has changed.
});
};
// The controller gets the model.
var Controller = function(model) {
this.model = model;
};
// The view calls this on the controller when a user selects a different customer
// in the select list.
Controller.prototype.onSelectedCustomerChanged = function(id) {
// 1) Update the model.
// 2) The model will fire an event after selecting the customer.
// 3) The view will be notified and updates its interface.
};
So in short it has the following characteristics:
Very good examples (I use alot of them in mine):
Comments