Pseudorandom Knowledge

Let the client do the work

Websites are increasingly built using Ajax and JavaScript. This has culminated in the single page application design. These are websites where the server is used only as a data store and all the heavy lifting is done in the client.

Writing this much client side code would be difficult without a good framework. Fortunately, there are many to choose from. Unfortunately, there are many to choose from. Most, if not all, of them are built on MV* principles, where the * stands for the fact that they often deviate from the MVC pattern.

Backbone.js

$(function () {
    var MainModel = Backbone.Model.extend({
        defaults: {
            greeting: 'Hello world'
        }
    });
 
    var MainView = Backbone.View.extend({
        tagName: 'h2',
        initialize: function () {
            this.model.on('change', this.render, this);
            this.render();
        },
        render: function () {
            this.$el.html(this.model.get('greeting'));
            $('body').html(this.$el);
        }
    });
 
    var AppRouter = Backbone.Router.extend({
        routes: {
            '': 'main'
        },
        main: function () {
            var model = new MainModel();
            var view = new MainView({ model: model });
            setTimeout(function () {
                model.set('greeting', 'Cruel world');
            }, 1700);
        }
    });
 
    new AppRouter();
    Backbone.history.start();
});

Backbone is one of the more popular frameworks. This example shows how models, views and routes are used to assemble the application. In addition there are collections which handle collections of models.

While some frameworks are very rigid in their structure Backbone is rather more flexible. There are some recommendations though. Use Underscore.js templates when rendering views. Use REST when getting data from the server. And you probably want to include jQuery even though the documentation likes to consider it optional.

There are plenty of extensions to Backbone. Most of which can be served from cdnjs together with Backbone itself and its dependencies.