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.

Advertisements

One thought on “Let the client do the work

  1. Pingback: Let Angular do the work | Pseudorandom Knowledge

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s