/ Maven

Backbone.Marionette - Skeleton of a JavaScript Web Application

Abstract: The present article will give a brief introduction to a way of building JavaScript based web applications using RequireJS (version 2.0.1), jQuery (version 1.7.2), Underscore (version 1.3.3.), Backbone.js (version 0.9.2), Backbone.Marionette (version 0.8.4), Handlebars (version 1.0.beta.6), TrafficCop (version 0.3.0), Maven(vesion 3.0.3), and Jetty (version 8.1.4.v20120524 used in embedded mode).

Acknowledgement: My gratitude goes to the open source community, to the above mentioned projects, and to the following guys:
David Sulc - A simple Backbone.Marionette tutorial
Mavenizing Javascript Projects

Be aware: Since this example serves a static web content you may simply load the index.html file, however be aware that doing so may result in

XMLHttpRequest cannot load file:///... Origin null is not allowed by Access-Control-Allow-Origin.

If this happens you can either do as told below or look at: stackoverflow

The final goal of this tutorial will be to create a very simple modular structure for displaying project names. Let's start. Here is what the structure of our final project will look like:

.
|-- pom.xml
`-- src
    |-- main
    |   `-- js
    |       `-- app
    |           `-- model
    |               `-- Project.js
    |               `-- Projects.js
    |           `-- view
    |               `-- ProjectView.js
    |               `-- ProjectsView.js
    |           `-- application.js
    |       `-- lib
    |           `-- backbone.js
    |           `-- backbone.marionette.js
    |           `-- handlebars-1.0.0.beta.6.js
    |           `-- require-jquery.js
    |           `-- TrafficCop.js
    |           `-- underscore.js
    |       `-- templates
    |           `-- project-template.html
    |           `-- projects-template.html
    |       `-- index.html
    |       `-- main.js
    `-- test
        `-- js

... and here is our pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>project-name</groupId>
    <artifactId>project-id</artifactId>
    <version>1.0</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>8.1.4.v20120524</version>
                <configuration>
                    <webAppConfig>
                        <contextPath>/${project.artifactId}</contextPath>
                        <baseResource implementation="org.eclipse.jetty.util.resource.ResourceCollection">
                            <resourcesAsCSV>src/main/js/,src/main/js/app</resourcesAsCSV>
                        </baseResource>
                    </webAppConfig>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The first thing we're going to need is a base index.html file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Project Knowledge Management</title>
    <script data-main="main" src="lib/require-jquery.js"></script>
</head>
<body>
<h1>Projects</h1>
<div id="content"></div>
</body>
</html>

As you can see (within the first highlighted row, line 5), this file has two references one to main which is actually a reference to main.js and one to require-jquery.js which you can download from here (this file contains jQuery inside, thus you don't need a separate jQuery). Note that the second highlighted row (line 9) will contain our future content (this is going to be our hook point linked to application.js). So what's inside main.js? Here it is:

require.config( {
    paths:{
        underscore:'lib/underscore',
        backbone:'lib/backbone',
        marionette:'lib/backbone.marionette',
        handlebars:'lib/handlebars-1.0.0.beta.6',
        TrafficCop:'lib/TrafficCop',
        app:'app/application',
        projects:'app/model/Projects',
        project:'app/model/Project'
    }
} );

require([ 'jquery', 'TrafficCop', 'underscore', 'backbone', 'marionette', 'handlebars', 'app','projects', 'project'],
        function ( $, TrafficCop, _, Backbone, Marionette, Handlebars, App, Projects, Project) {
                  Backbone.Marionette.TemplateCache.loadTemplate = function(templateId, callback){
                    var tmpId = templateId.replace("#", "");
                    var url = "templates/" + tmpId + ".html";
                    var promise = $.trafficCop(url);
                    promise.done(function(template){
                      callback.call(this, Handlebars.compile($(template).html()));
                    });
                  }

            var projects = new Projects([
                             new Project({ name: 'First Project' }),
                             new Project({ name: 'Second Project }),
                             new Project({ name: 'Third Project' })
                             ]);
                    App.start({projects: projects});
        }
);

Yes, you've guessed it, the fun start here. The necessary ingredients you can download (and place in the lib folder) from here: underscore, backbone, backbone.marionette, handlebars, TrafficCop. Well that was all of the external libs, now comes the time to build our internal business project structure. First we are going to need a model of a project, thus we are going to create a simple Backbone.js model within a file called Project.js:

define(['backbone'], function(Backbone){
         var Project = Backbone.Model.extend({});
         return Project;
});

As you can see, there is not much interesting inside since our example is really only a skeleton. After we have our main domain model, we are going to need a collection of them, thus comes the Projects.js:

define(['backbone', 'model/Project'], function(Backbone, Project){
         var Projects = Backbone.Collection.extend({
           model: Project

         });
         return Projects;
});

So far so good. Next we are going to need an entry point, that being the application.js:

 
define(['view/ProjectsView'], function(ProjectsView){
var App = new Backbone.Marionette.Application();
         App.addRegions({
           mainRegion: "#content"
         });

         App.addInitializer(function(options){
           var projectsView = new ProjectsView({
             collection: options.projects
           });
           App.mainRegion.show(projectsView);
         });
         return App;
});

Note line 4, this is the reference to our hook point in the index.html file. As you can see from line 8, our App has a reference to a view called ProjectsView for which we have a JavaScript file called ProjectsView.js and having the following content:

 
define(['marionette', '../view/ProjectView'], function(Marionette, ProjectView){
         var ProjectsView = Backbone.Marionette.CompositeView.extend({
         tagName: 'table',
         id: 'projects',
         className: 'table-striped table-bordered',
         template: '#projects-template',
         itemView: ProjectView,

         appendHtml: function(collectionView, itemView){
         collectionView.$("tbody").append(itemView.el);
         }
         });
         return ProjectsView;
});

The ProjectsView is a composite view based on ProjectView described in ProjectView.js:

 

define(['marionette'], function(Marionette){
         var ProjectView = Backbone.Marionette.ItemView.extend({
          template: '#project-template',
          tagName: 'tr',
          className: 'project'
         });
         return ProjectView;
}); 

The highlighted rows in both ProjectsView.js and ProjectView.js indicate the names of the required templates which can be found in templates directory. The first, projects-template.html, looks like this:

<script id="projects-template" type="text/x-handlebars-template">
    <thead>
    <tr class='header'>
        <th>Project Name</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</script>

The second, project-template.html, looks like this:

<script id="project-template" type="text/x-handlebars-template">
    {{name}}
</script>

Running our example is as simple as doing mvn jetty:run. Oh, and of course you can go to localhost:8080 and browse the result.

Ivan Hristov

Ivan Hristov

I am a lead software engineer working on software topics related to cloud, machine learning, and site reliability engineering.

Read More