Organizing Backbone Applications - Structure, Optimize, and Deploy

Exclusive offer: get 50% off this eBook here
Backbone.js Patterns and Best Practices

Backbone.js Patterns and Best Practices — Save 50%

A one-stop guide to best practices and design patterns when building applications using Backbone.js with this book and ebook

$23.99    $12.00
by Swarnendu De | January 2014 | Open Source

Backbone itself doesn't provide any application structure or guidance on how to organize the application source code. This makes it quite difficult for beginner-level programmers to understand how to create a folder structure, add proper namespaces, load script files in the appropriate order, and follow patterns to create a robust app architecture. We will see how to do so in this article by Swarnendu De, author of Backbone.js Patterns and Best Practices.

(For more resources related to this topic, see here.)

Creating application architecture

The essential premise at the heart of Backbone has always been to try and discover the minimal set of data-structuring (Models and Collections) and user interface (Views and URLs) primitives that are useful when building web applications with JavaScript.

Jeremy Ashkenas, creator of Backbone.js, Underscore.js, and CoffeeScript

As Jeremy mentioned, Backbone.js has no intention, at least in the near future, to raise its bar to provide application architecture. Backbone will continue to be a lightweight tool to produce the minimal features required for web development. So, should we blame Backbone.js for not including such functionality even though there is a huge demand for this in the developer community? Certainly not! Backbone.js only yields the set of components that are necessary to create the backbone of an application and gives us complete freedom to build the app architecture in whichever way we want.

If working on a significantly large JavaScript application, remember to dedicate sufficient time to planning the underlying architecture that makes the most sense. It's often more complex than you may initially imagine.

Addy Osmani, author of Patterns For Large-Scale JavaScript Application Architecture

So, as we start digging into more detail on creating an application architecture, we are not going to talk about trivial applications or something similar to a to-do-list app. Rather, we will investigate how to structure a medium- or large-level application. After discussions with a number of developers, we found that the main issue they face here is that there are several methodologies the online blog posts and tutorials offer to structure an application. While most of these tutorials talk about good practices, it becomes difficult to choose exactly one from them. Keeping that in mind, we will explore a number of steps that you should follow to make your app robust and maintainable in the long run.

Managing a project directory

This is the first step towards creating a solid app architecture. We have already discussed this in detail in the previous sections. If you are comfortable using another directory layout, go ahead with it. The directory structure will not matter much if the rest of your application is organized properly.

Organizing code with AMD

We will use RequireJS for our project. As discussed earlier, it comes with a bunch of facilities such as the following:

  • Adding a lot of script tags in one HTML file and managing all of the dependencies on your own may work for a medium-level project, but will gradually fail for a large-level project. Such a project may have thousands of lines of code; managing a code base of that size requires small modules to be defined in each individual file. With RequireJS, you do not need to worry about how many files you have—you just know that if the standard is followed properly, it is bound to work.
  • The global namespace is never touched and you can freely give the best names to something that matches with it the most.
  • Debugging the RequireJS modules is a lot easier than other approaches because you know what the dependencies and path to each of them are in every module definition.
  • You can use r.js, an optimization tool for RequireJS that minifies all the JavaScript and CSS files, to create the production-ready build.

Setting up an application

For a Backbone app, there must be a centralized object that will hold together all the components of the application. In a simple application, most people generally just make the main router work as the central object. But that will surely not work for a large application and you need an Application object that should work as the parent component. This object should have a method (mostly init()) that will work as the entry point to your application and initialize the main router along with the Backbone history. In addition, either your Application class should extend Backbone.Events or it should include a property that points to an instance of the Backbone.Events class. The benefit of doing this is that the app or Backbone.Events instance can act as a central event aggregator, and you can trigger application-level events on it.

A very basic Application class will look like the following code snippet:

// File: application.js define([ 'underscore', 'backbone', 'router' ], function (_, Backbone, Router) { // the event aggregator var PubSub = _.extend({}, Backbone.Events); var Application = function () { // Do useful stuff here } _.extend(Application.prototype, { pubsub: new PubSub(), init: function () { Backbone.history.start(); } }); return Application; });

Application is a simple class with an init() method and a PubSub instance. The init() method acts as the starting point of the application and PubSub works as the application-level event manager. You can add more functionality to the Application class, such as starting and stopping modules and adding a region manager for view layout management. It is advisable to keep this class as short as you can.

Using the module pattern

We often see that intermediate-level developers find it a bit confusing to initially use a module-based architecture. It can be a little difficult for them to make the transition from a simple MVC architecture to a modular MVC architecture. While the points we are discussing in this article are valid for both these architectures, we should always prefer to use a modular concept in nontrivial applications for better maintainability and organization.

In the directory structure section, we saw how the module consists of a main.js file, its views, models, and collections all together. The main.js file will define the module and have different methods to manage the other components of that module. It works as the starting point of the module. A simple main.js file will look like the following code:

// File: main.js define([ 'app/modules/user/views/userlist', 'app/modules/user/views/userdetails' ], function (UserList, UserDetails) { var myVar; return { initialize: function () { this.showUserList(); }, showUsersList: function () { var userList = new UserList(); userList.show(); }, showUserDetails: function (userModel) { var userDetails = new UserDetails({ model: userModel }); userDetails.show(); } }; });

As you can see, the responsibility of this file is to initiate the module and manage the components of that module. We have to make sure that it handles only parent-level tasks; it shouldn't contain a method that one of its views should ideally have.

The concept is not very complex, but you need to set it up properly in order to use it for a large application. You can even go for an existing app and module setup and integrate it with your Backbone app. For instance, Marionette provides an application infrastructure for Backbone apps. You can use its inbuilt Application and Module classes to structure your application. It also provides a general-purpose Controller class—something that doesn't come with the Backbone library but can be used as a mediator to provide generic methods and work as a common medium among the modules.

You can also use AuraJS (https://github.com/aurajs/aura), a framework-agonistic event-driven architecture developed by Addy Osmani (http://addyosmani.com) and many others; it works quite well with Backbone.js. A thorough discussion on AuraJS is beyond the scope of this book, but you can grab a lot of useful information about it from its documentation and examples (https://github.com/aurajs/todomvc). It is an excellent boilerplate tool that gives your app a kick-start and we highly recommend it, especially if you are not using the Marionette application infrastructure. The following are a few benefits of using AuraJS ; they may help you choose this framework for your application:

  • AuraJS is framework-agnostic. Though it works great with Backbone.js, you can use it for your JavaScript module architecture even if you aren't using Backbone.js.
  • It utilizes the module pattern, application-level and module-level communication using the facade (sandbox) and mediator patterns.
  • It abstracts away the utility libraries that you use (such as templating and DOM manipulation) so you can swap alternatives anytime you want.

Managing objects and module communication

One of the most important ways to keep the application code maintainable is to reduce the tight coupling between modules and objects. If you are following the module pattern, you should never let one module communicate with another directly. Loose coupling adds a level of restriction in your code, and a change in one module will never enforce a change in the rest of the application. Moreover, it lets you re-use the same modules elsewhere. But how can we communicate if there is no direct relationship? The two important patterns we use in this case are the observer and mediator patterns.

Using the observer/PubSub pattern

The PubSub pattern is nothing but the event dispatcher. It works as a messaging channel between the object (publisher) that fires the event and another object (subscriber) that receives the notification.

We mentioned earlier that we can have an application-level event aggregator as a property of the Application object. This event aggregator can work as the common channel via which the other modules can communicate, and that too without interacting directly.

Even at the module-level, you may need a common event dispatcher only for that module; the views, models, and collections of that module can use it to communicate with each other. However, publishing too many events via a dispatcher sometimes makes it difficult to manage them and you must be careful enough to understand which events you should publish via a generic dispatcher and which ones you should fire on a certain component only. Anyhow, this pattern is one of the best tools to design a decoupled system, and you should always have one ready for use in your module-based application.

Summary

This article dealt with one of the most important topics of Backbone.js-based application development. At the framework level, learning Backbone is quite easy and developers get a complete grasp over it in a very short period of time.

Resources for Article:


Further resources on this subject:


Backbone.js Patterns and Best Practices A one-stop guide to best practices and design patterns when building applications using Backbone.js with this book and ebook
Published: January 2014
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Swarnendu De

Swarnendu De is the director of Innofied Solution Pvt. Ltd.( http://www.innofied.com ), a specialized mobile, web, and game development company. He manages technical operations and leads the JavaScript development team there. For the last seven years, he has been working with numerous JavaScript technologies including Backbone.js, Node.js, ExtJS, Sencha, and so on, and has developed more than 50 complex JavaScript-based applications thus far. He regularly writes at his personal blog, company blog, and the Tuts+ network. He has been working with Backbone.js for the last 2 years and has developed multiple, large, and complex Backbone.js-based applications using this technology.

Swarnendu lives in Kolkata—the city of joy. He loves travelling, photography, and spending time with his family. You can reach him through his website at http://www.swarnendude.com or via Twitter at @swarnendude.

Books From Packt


Backbone.js Testing
Backbone.js Testing

 Instant Backbone.js Application Development [Instant]
Instant Backbone.js Application Development [Instant]

Backbone.js Cookbook
Backbone.js Cookbook

Getting Started with Backbone Marionette
Getting Started with Backbone Marionette

Ext JS 4 First Look
Ext JS 4 First Look

 Instant IntroJs [Instant]
Instant IntroJs [Instant]

 Learning Ext JS 3.2
Learning Ext JS 3.2

KnockoutJS Starter [Instant]
KnockoutJS Starter [Instant]


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
9
g
P
C
1
a
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software