Dev: Enterprise Backbone.js Project Setup

Today I want to discuss the how’s and why’s of a Backbone.JS ( implementation.

Ultimately, doing client side MVC, you come to face to face with Google’s popular Angular framework. Many people will question you if you use anything but Angular. Another architect I met summed it up well though. He said that if you have to teach a team Angular, it takes some time, because you have to learn the “Angular” way of doing things. using Backbone, it’s straight Model View Controller setup. There’s really nothing new in there to learn, and I’m a big fan of eliminating learning curves for teams when possible.

So, that’s as good a reason as any. Now, once you decided to go down the Backbone road, there’s a lot of opinionated decisions you have to make. Ironic, since Backbone is supposed to be “opinionated” according to some definitions. Personally I think there were still too many choices left up to the developer… ergo pitfalls.

Folder Structure
The first thing you have to decide is how you want to setup your project.
If you’re smart, you want to do something that will make sense to programmers that come later.
Here is what we ended up using:

     |-- [scss]
     |-- [img]
     |-- [vendor] (where you stuff 3rd party plugins)
     |-- [js]
         |-- [lib] (external scripts: handlebars, foundations, i18next, etc)
         |-- [collections] (your backbone extended collections)
         |-- [models] (your backbone extended models)
         |-- [templates] (handlebars templates for programmatic views)
         |-- [views] (your backbone extended views)
         |-- app.js (configure your backbone app)
         |-- main.js
         |-- require-config.js (setup require.js dependencies)
         |-- router.js (setup your routes)
     |-- [locales]
     |-- [tests]
     |-- Gruntfile.js (builds the project)
     |-- package.json (contains all the packages...)
   |-- server.js (contains the Node.js website configuration)
   |-- build.js (optimizes javascript files)
     |-- 404.html
     |-- favicon.ico
     |-- index.html

This came from Mathew LeBlanc’s excellent Backbone.js course on Six months ago, I tried to follow Addy Osmani’s Backbone book, only to find it’s source code was out of date and didn’t work. There are some good ideas in it, but, the code’s out of date.

Here’s a short description of the 3rd party scripts we started with:

Style Sheets
Foundation handles the mobile-first design.
For our own CSS organization, we follow the SMACSS (Scalable and Modular Architecture for CSS – approach. On top of that, we’re using SASS with Compass which generates the .scss files.

Scalable and Modular Architecture for CSS

SASS and LESS are popular CSS authoring frameworks (Foundation is built on SASS, so, it aligns better than LESS for us). That means they manage and compile CSS code for your project. To get the build/compile functionality, we’re using Compass, which is written in Ruby, so you need Ruby installed for it to work.

The folder structure ends up looking like this:

     |-- [css]
         |-- main.css (generated)
     |-- [scss]
         |-- [base]
         |-- [layout]
         |-- [module]
         |-- [state]
         |-- [theme]
         |-- _mixins.scss
         |-- _variables.scss
         |-- main.scss

Now let’s explain that a bit.
The base structure comes from SMACSS.
main.scss: this is automatically generated via imports from other scss files. This is the compilation process, and thus the only CSS file that will be minified.
_mixins.scss: Custom mixins.
_variables.scss: Contains scss variables (colors/fonts).

You define styles in base, layout, module, state, and theme.
So if you create a Backbone View called “medical-survey.js” then the handlebars template would be “medical-survey.html” and the style sheet would be “medical-survey.scss”

On small projects, you might think that’s annoying, but on a large scale project, this is very handy. It allows us to chunk out work, while still compiling it all into a single, minified styles sheet at the end.

The important part of SASS comes with this setup line of code:

sass --watch scss:css --style compressed

This tells the SASS (running via Ruby/Compass) to watch the folders under scss. SASS will find all the .scss files and import them into a single main.scss file. This file will be compiled into the final main.css. This file *will* come out very large. Even with the white space stripped out, it will often be huge and can slow down your site unacceptably…

Minification and Compression
So, if you implemented Require.js in the project to handle the efficient loading of Javascript files. What do you do about the massive CSS file you just generated using SASS above? If you are using Node.js, there’s a solution in the middleware. Compression.

The website discussing it is here:

This will use gzip to decrease the file size when loading the website.

There’s a lot of thought, effort, and detail complete missing from this blog. But if you have any questions, please let me know. My goal is always to help teams use simple and tested methods, but when we use newer techniques, we’re faced with not being able to get the best information about using it. This is definitely a major caveat to using technology developed in the last 3-5 years. We often do it anyway because new techniques are usually developed to resolve an annoyance we’ve been dealing with. Node.js resolves the annoyance of web servers like IIS and Apache being a bit slower and complex than we would like. It also adapts well in scalable scenarios.

Likewise, I don’t see any reasonable way to avoid the modern problem of having ridiculous amounts of Javascript and CSS. It’s just the modern problem. We don’t want to take the time hit to a project (and should not) to reinvent the wheel by rewriting things other developers have done via JQuery and other handy tools.
I have been coding CSS since 1998 and what began as a tool to *simplify* applying global (and thus branded) styles has grown into a monster; albeit a highly useful one, the most developers simply won’t take the time to really understand. SASS and LESS are simply ways for these developers to deal with the massive amount of CSS to compile it down into at least one file. And Compression makes it manageable. But it doesn’t solve the root problem:
The CSS cat has gotten out of the bag and no one is quite sure hot to get it back in.

The other root problem is unsolvable: the companies building the browsers will never follow a standard unless it’s the “standard” they made. Just accept it and you’ll be happier.

Setup: VirtualBox 4.3.6, Ubuntu 13.10 CLI, Node.js, Forever.js

In my last post I covered a popular implementation of BackboneJS in Visual Studio.

I was not happy with it. Primarily because mixing a JavaScript Client-Side MV* solution with a ASP.Net Server-Side MVC solution feels clunky.
So, I’ve set out to do a clean Backbone setup. Which led me to the desire for a clean Web Server, which led me to NginX, and then to Node.
So, this post is a walkthrough of setting up a Node Web Server in Virtual Box.

The Steps:

  1. Install Virtual Box
  2. Create a Virtual Machine with Ubuntu 13.10 64bit CLI iso
  3. Install Guess Additions for your VBox version
  4. Install Node
  5. Install Express
  6. Install Forever

For brevity, I will skip the Virtual Box and Guest Additions steps as I’ve already covered this before.
The ISO for Ubuntu 13.10.CLI is here:
For this walkthrough, ensure you get the Server version: 64-bit PC (AMD64) server install image

In the settings for the VM, you can do what you like or use what I did:

  • RAM: 4gb
  • Select “create a virtual hard drive now”
  • choose VDI
  • Use dynamically allocated
  • Give it 20GB
  • Go to “settings”
  • Select General –> Advance
  • Enable shared clipboard and drag ‘n’ drop
  • Uncheck the mini toolbar
  • Go to storage
  • Click the empty disk under controller: IDE
  • Click the little disk icon with a down arrow and select your Ubuntu server iso.
  • Networking:
  • Leave as NAT unless you know how to setup a bridged connection on your computer

ERROR ALERT: If you get the error: VT-x is disabled in the BIOS.

  • Reboot your machine into BIOS mode.

  • Find the Virtualization Setting
  • Enable it (sometimes there are two)
  • Save and Exit
  • Error should be fixed

Start the server and it will go into the Ubuntu install screens

ERROR ALERT: If you get the error: This kernel requires an x86 CPU, but only detected i686 CPU.
FIX: Close the machine, open settings, and change your OS to the Ubuntu/Linux 64 bit version.

Setup your username and password and jot that down for later.

When you get to the Software Selection screen; choose LAMP or SSH.
Azure Note: When you setup Ubuntu on a VM in Azure, this choice is made for you; SSH I believe.

Once complete, a command line interface will come back and ask you for the server login.
Enter your username and password

There are many, many ways to install Node on Unix. If you’re searching the intertubes, you will find a few different scenarios:

  • Installing from source on git. I don’t suggest this route
  • Installing through apt-get; this is a nice and easy route
  • Installing through NVM; this is also nice and easy
  • Installing straight from your Ubuntu; also nice and easy

There’s no “right way” so I will cover from git and from apt-get.
If you watch the training on Node; Joseph LeBlanc uses the NVM so he can quickly switch out which version of Node he is using.

Here is how to install it from GitHub…
First, install dependencies:

  sudo apt-get install g++ curl libssl-dev apache2-utils
  sudo apt-get install git-core
  sudo apt-get install make
  Then install:
  git clone git://
  cd node
  sudo make install

Here is how to install it from apt-get

sudo apt-get install nodejs

cd node/
sudo nano hello_world.js

var http=require('http');

http.createServer(function (req,res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node\n');
}).listen(8080, "");

console.log('server running at port http://localhost:8080');

What you’ve done here is very rudimentary, but core.
You’ve bought in a core Node module called HTTP and set it to a local variable.
Then you used that local variable to access the “createServer” function to start a basic HTTP server.
Then you configured the “res”-response variable of that server to write out an HTTP 200 with a content type of text (not HTML).
Then you tell it to “listen” on port 8080 of your localhost.
And finally you write to the console where it should be running.

Save and exit.
Now use the “node” command to run your script.

sudo node hello_world.js

At this point you can open a browser to http://localhost:8080 and see your message.

This brings you to the first challenge of Node: How do you make it run as a service?
There are several ways, I will cover the Forever solution.


sudo npm install forever -g

This will use the Node Package Manager to install forever (-g makes it a global installation, so it’s usable at the command line).

Once complete:

sudo forever start hello_world.js

Now your node server is running as a service and if it dies, Forever will restart it.

Dev: Visual Studio 2013 Single Page Application with BackBoneJS

As part of my exploration from the last blog post I have been digging into BackBoneJS. Here I take a look at getting started with BackBoneJS in a Microsoft environment. Ultimately, I don’t think this is a very clean solution, so I’ll follow up with another that’s not integrated with ASP.Net’s MVC.

There’s a few requirements for this post.

Our goals with this website is to get a basic MVC website up and running using the BackBoneJS framework.
You can learn more about BackBoneJS here:
So, once you’ve got Visual Studio installed and running, and the BackBoneJS template installed, go ahead and create a new Visual C#  Web ASP.NET Web Application. It should look like this:
This will give you a new window of options; choose the Single Page Application.
Okay, let that build the solution. If you want to see what it does right off, run it with F5.
This theme uses the popular Bootstrap theme (CSS3) to achieve a “responsive” look and feel. Responsive simply means the website will attempt to mold itself to whatever screen size your users browse the site with. Be that a tiny screen through a smartphone or a big screen through a desktop computer. This concept can save you a lot of development time down the road when clients ask for a version of your site to work on their iPad. Responsive is better, in my opinion, than a mobile version of a website. This comic attempts to explain precisely why:

You can learn more about Bootstrap at their website:

We’re using Bootstrap with this theme automatically, but I don’t want to use the default Bootstrap theme. It’s unoriginal and sort of lazy to use the default theme. So, I’ll go to a website that offers other themes that work with Bootstrap: and download the “Slate” theme. Save the “bootstrap.css” and “bootstrap.min.css” to your projects “Content” folder. This will overwrite the defaults that came with the project.

Centering images in the JumboTron

Personally, I’m going for a pretty simple page here. A centered logo at the top, followed by some page content with images. For the “header” section of a web page, Bootstrap delivers JumboTron. In their words, “A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.” You can learn more about the JumboTron on their website:

What JumboTron does not do out of the box is give you a class to center your image. Developers will waste hours trying to hack the CSS, but, CSS requires finesse, not muscle. Here’s the code that accomplishes a centered image without much fuss:

<div class="jumbotron">
<div class="row well well-lg">
<div class="col-md-6 col-md-offset-3">
             <img src="~/Content/logo_bw_trans.png" alt="header" class="img-responsive text-center" />

I found this, like almost all code snippets, on stackoverflow:

The Grid System

Bootstrap uses a popular CSS technique for laying out web pages. In bygone years, this was popularized by the creators of CSS frameworks like the 960,, and BluePrint, From my perspective, these CSS frameworks became popular when UI developers realized the middle tier devs weren’t going to take the time to learn CSS and would keep using HTML tables to layout sites. So, they made CSS frameworks to try to help those same devs. Even then it took several years for frameworks like Bootstrap to make it easier. I believe Twitter’s Bootstrap may have grown up from HTML5Boilerplate, but, I don’t know.

The default template starts me off with a 3 section layout, but I only want 2. So, here is what they give us in the template:

<div class="row">
<div class="col-md-4">
<div class="col-md-4">
<div class="col-md-4">

Without understanding the grid system, you can quickly see there’s some logic to this. The class “col-md-4” seems to have a naming convention to it. It does and it is explained in detail here: If you’re guess was that they all add up to 12, then you’re right! I want 2 columns, so mine is reduced to this:

<div class="row">
<div class="col-md-6">
<div class="col-md-6">

Now, I want four rows of content with two columns, so I’ll just copy and paste that a few times and fill in the content. Once that’s done I want a section at the bottom with a big button telling my users what to do. As you are dropping content and images onto the page, you might notice that your images don’t come out the size you made them.

So if we look at this piece of code:

<img src="~/Content/dojo-path.png" alt="header" class="img-responsive text-center" />

You can see the class “img-responsive.” This is one of those magic Bootstrap CSS3 classes that makes your website scale for smartphones or big websites. While you may be tempted to take this off, I advise you leave it and let Bootstrap do what it knows best.
At the end of the page I want an email sign-up form so I can keep in touch with my prospective customers. Email sign up forms are something that almost every website in existence uses, so, there should be very little coding here. But you searched through the Bootstrap website and didn’t find it. Luckily there’s another website,, and if you do a quick search on sign up forms, you’ll see there are a few to choose from. I liked this one:

Well, that’s enough to get your basic functionality so you can wire in some email server. But I’d like to go a bit further.
I already have an account with MailChimp, a popular mailing list website,, so let’s just see what it takes to wire up a signup form to a mailchimp auto-responder list. So, if you have a mailchimp account, you can get your basic code for a signup form and combine with some of the Bootstrap visual enhancements and end up with code like this:

<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup" class="text-center">
<form action="http:/url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<input type="email" value="" name="EMAIL" class="span6" id="mce-EMAIL" placeholder="email address" required>
                <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_31c7d2f366bf7abc8b70e0bf3_64a94b06cb" value=""></div>

                    <button type="submit" id="mc-embedded-subscribe" class="btn btn-default btn-lg">
                        <span class="glyphicon glyphicon-off btn-lg"></span> Subscribe
<!--End mc_embed_signup-->

This gives you a decent looking sign up like this:
Which works. And when you hit submit, it opens a new window from mailchimp for the user to confirm their information… which sucks.
What I really want is to use the MailChimp API so you can handle the request from within your application. Since we’re not using WordPress or Drupal, we need to do this with ASP.Net. Unsurprisingly, someone has already done this, and their GitHub project is here:

So, let’s get to it. We’re going to install this into our project using the Package Manager Console [Tools–Library Package Manager–Package Manager Console] and type: Install-Package MailChimp.NET

That should get you a bunch of successful messages. Next I need my API Key from MailChimp. That’s covered here: essentially, it’s: primary dashboard–Account Settings–Extras–API Keys

Okay, you’ve imported the MailChimp API, you have your secret API key, now it’s time to go to your Controller and write your function.
Throw these imports into the top of the Controller:

using MailChimp;
using MailChimp.Lists;
using MailChimp.Helper;
Then add a function:
public void SubscribeEmail() {
            MailChimpManager mc = new MailChimpManager(&#8220;YourApiKeyHere-us2&#8243;);
            //  Create the email parameter
            EmailParameter email = new EmailParameter()
                Email = &#8220;;
            EmailParameter results = mc.Subscribe(&#8220;YourListID&#8221;, email);

But that will wait till next time.

© Copyright Duke Hall - Designed by Pexeto