JavaScript MVC frameworks

8:27 PM Xun 2 Comments

MVC has been having a great run for a while (a long while). It was introduced in the computer's stone age (the 70s, the first micro processor, the floppies, main frames), morphed into a well-accepted architectural theory in the bronze age (the 80s, IBM, computers for personal use became possible). Then computers and the internet and mobile devices became our overlords, exploding in power and complexity. To rein in the complexity and keep us from being entangled in the web of our own weaving, MVC becomes the default and de facto application architecture.

We all know now the three legs of the MVC stool:
Models - Data, business rules, logic, etc.
Views - Presentation layer, be it a chart, a table, an image gallery. The front end of things
Controllers - The link between model and view, the commander-in-chief that takes signals and issues command.
 


On the server side, we have a set of big players and well established design patterns and architectures. Ruby is the trail blazer that first goes MVC in full throttle. ASP .net MVC soon followed suit, moved over from the web form development model where UI is tightly coupled with the code-behind logic. ASP .net MVC provides powerful view engine, various routing techniques, and flexible controllers that accept and return data in the formats requested.

On the client/JavaScript side, the playground is always more diverse therefore more interesting and more confusing.

JavaScript MVC frameworks

Briefly searching the web on JavaScript MVC frameworks, you get a dozen and still counting. According to infoQ's research, the following are the top MVC frameworks:

Backbone.js: Provides models with key-value binding and custom events, collections, and connects it all to your existing API over a RESTful JSON interface.
AngularJS: A toolset based on extending the HTML vocabulary for your application.
Ember.js: Provides template written in the Handlebars templating language, views, controllers, models and a router.
Knockout: Aims to simplify JavaScript UIs by applying the Model-View-View Model (MVVM) pattern.
Agility.js: Aims to let developers write maintainable and reusable browser code without the verbose or infrastructural overhead found in other MVC libraries.
CanJS: Focuses on striking a balance between size, ease of use, safety, speed and flexibility.
Spine: A lightweight framework that strives to have the most friendly documentation for any JavaScript framework available.
Maria: Based on the original MVC flavor as it was used in Smalltalk - aka "the Gang of Four MVC".
ExtJS: Amongst other things offers plugin-free charting, and modern UI widgets.
Sammy.js: A small JavaScript framework developed to provide a basic structure for developing JavaScript applications.
Stapes.js: A tiny framework that aims to be easy to fit in an existing codebase, and because of its size it's suitable for mobile development.
Epitome: Epitome is a MVC* (MVP) framework for MooTools. soma.js: Tries help developers to write loosely-coupled applications to increase scalability and maintainability.
PlastronJS: MVC framework for Closure Library and Closure Compiler. rAppid.js: Lets you encapsulate complexity into components which can be easy used like HTML elements in your application.
Serenade.js: Tries to follow the ideas of classical MVC than competing frameworks.
Kendo UI: Combines jQuery-based widgets, an MVVM framework, themes, templates, and more.


Why so many frameworks? Why JavaScript MVC? What is MVC in JavaScript? Which one or ones to choose?

Well, if you were me, you probably would try to dismiss all those frameworks as noise. You may just want to bury you head in the sand, keep piling another jQuery plugin or another Ext js feature. But before long, the chorus of MVC became deafening, and you found your project on the JavaScript gradually spiraled out of control, and it becomes more and more difficult to track what triggers from what controls have changed the state of your data. The JavaScript become yet again become a multi-million lines of mess.

So think again about a JavaScript MVC framework.

Flavors of JavaScript MVC

MVC on the JavaScript side is a little different from the server side MVC you know, or the ASP .net MVC i know. In fact, MVCs are a little different from the JavaScript frameworks within. First and foremost, the frameworks try to clearly separate data and presentation, views and models.

Models: data that flows underneath your site. More precisely, data models that represents the structure/schema of your data. Data relationship, constraints can be defined and verified. Think of a user data model, it will have typical elements like age, gender, name, etc.

Views: layout, templates and interface. The side that your users can see and manipulate. They are your models marked up as photo galleries, task list, a table of data, etc.

Different frameworks have different takes when it comes to controllers. For some, the line between controllers and views are blurred, or views simply initiate the actions that theoretically would have belong to controllers. For example, backbone.js. Others do make controllers an command center that launches an application, initializes data models, monitors data changes and calls for appropriate actions. For example, Ext Js, Ember js.

There are also other flavors of JavaScript MVC. The most notably, the MVVM (Model-View-View Model) implemented by Knockout.js. Knockout.js has your typical views and models, however the controller part is termed as View Models, which bind DOM elements with data models and automatically refresh UI when data changes.

It is hard to get to know therefore evaluate each of the frameworks which all carry with them oh-so-good halos and incredibly cool demos and live websites, so we have to heavily rely on word of mouth that is circling on the internet. Some articles provide just that, for example:

Essential JavaScript: the top five MVC frameworks
Journey Through The JavaScript MVC Jungle

Backbone.js
Of the JavaScript frameworks, Backbone.js sits on top of the list and it has an impressive list of heavy-weight players, such as USA Today, LinkedIn mobile. Backbone.js has a collection of methods that manipulate data models, get/set, construct, make a collection, push/pop, extend. The whole backbone.js is revolving around data models and data handling logic.


var user = Backbone.Model.extend({
    name: 'Annoymous',
    age: 18,
    initialize: function() { ... },

    email: function() { ... }
});

Knockout.js
Knockout.js is particular hit with ASP .net MVC, I do not know why. And the heart of Knockout.js is view-model.

The following (from Creating a Dynamic UI with Knockout.js)populates a products array from data requested from a web API.
function ProductsViewModel() {
    var self = this;
    self.products = ko.observableArray();

    // New code
    var baseUri = '@ViewBag.ApiUrl';
    $.getJSON(baseUri, self.products);
}

Ext Js
Dealing mostly with Ext Js in my professional life, I have to give Ext Js MVC a mention. Ext Js 4 makes data packages center of its library, it also has an extensive set of data model mechanisms to define, validate, populate and manipulate data. As typical of Ext Js, it goes on the verbose mode. An Ext Js MVC application would have the following file structure:

 
 Ext Js Controller establishes awareness of its view through the init method:
Ext.define('AM.controller.Users', {
    extend: 'Ext.app.Controller',
 
    init: function() {
        this.control({
            'viewport > panel': {
                render: this.onPanelRendered
            }
        });
    },
 
    onPanelRendered: function() {
        console.log('The panel was rendered');
    }
});
And an Ext Js View use an Ext Js component for display.
Ext.define('AM.view.user.List' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.userlist',
 
    title : 'All Users',
 
    initComponent: function() {
        this.store = {
            fields: ['name', 'email'],
            data  : [
                {name: 'Ed',    email: 'ed@sencha.com'},
                {name: 'Tommy', email: 'tommy@sencha.com'}
            ]
        };
 
        this.columns = [
            {header: 'Name',  dataIndex: 'name',  flex: 1},
            {header: 'Email', dataIndex: 'email', flex: 1}
        ];
 
        this.callParent(arguments);
    }
});
So which JavaScript MVC framework would you choose?

References: 

The MVC Application Architecture
Essential JavaScript: the top five MVC frameworks
Journey Through The JavaScript MVC Jungle
Backbone.js
Knockout.js

2 comments:

  1. The below website is developed using Backbone.js

    Backbone.js Course

    ReplyDelete
  2. What is a framework?

    Some time ago I asked "What is a framework?". I liked the following answer:

    In the case of a framework, your code is called by it. In the case of a library, your code call it. Rails is a framework, and provides libraries too.
    Our users are software engineers who care about doing JavaScript development the right way. They care about things like test driven development, performance, code quality, structure and maintainability.

    JavaScriptMVC makes it simple to do all these things and more.
    More Here: AngularJS

    ReplyDelete