Backbone.js Namespacing
Add a few Views and a Collection to a quick Backbone demo and the global scope fills up fast. UserView, UserModel, appRouter, and a dozen helpers all sit on window, where any script can clobber them and nothing tells you how the pieces relate. Namespacing is the simplest cure, and on classic Backbone projects it was one of the first things experienced developers reached for.
This guide shows two ways to namespace a Backbone app: the lightweight global object pattern, and the cleaner module based approach. Examples run on Backbone.js 1.6.0.
What you'll learn
- Why namespacing matters
- The global object pattern
- Avoiding the global scope entirely
- Organizing a growing app
- A worked example
- Common pitfalls
Why namespacing matters
Backbone does not impose any structure on where your classes live, so by default they land on the global object. That works for a single demo and breaks down everywhere else. Two scripts can define the same global, a typo silently overwrites a class, and a newcomer has no map of how Models, Views, and Collections relate.
A namespace is just one object that owns the rest. Instead of a hundred globals you expose one, and everything hangs underneath it. That single change makes an app easier to read, safer to extend, and far less likely to collide with a third party script.
The global object pattern
The quickest approach is a single application object created once, with sub objects for each kind of class. No build tooling is required.
Creating an app namespace
window.App = window.App || {
Models: {},
Views: {},
Collections: {},
Routers: {}
};
Attaching Models, Views, and Collections
Every class is defined onto the namespace rather than as a bare global, so the relationships are obvious at a glance.
App.Models.User = Backbone.Model.extend({ defaults: { name: "" } });
App.Views.User = Backbone.View.extend({
render: function () { this.$el.text(this.model.get("name")); return this; }
});
Avoiding the global scope entirely
The object pattern still puts one name on window. If you want nothing global at all, a module loader removes even that.
Namespacing through modules
With RequireJS or ES modules, each file returns its class and other files import it by path. The folder structure becomes the namespace, no shared object is needed, and the loader guarantees nothing leaks. This is the same idea covered in the modular Backbone example, applied here to keep the global scope completely empty.
Organizing a growing app
Once you have a namespace, how you arrange it decides whether it stays readable as the app grows.
Grouping by feature
On larger apps, grouping by feature often beats grouping by type. A App.Users branch that holds the user Model, View, and Collection together keeps related code in one place, which is easier to navigate than three parallel folders.
Keeping the namespace shallow
Resist deep chains like App.Features.Users.Views.List.Item. Every extra level is more to type and more to break. Two levels handle almost every app, and anything deeper is usually a sign the structure needs flattening.
A worked example
The pieces come together in a short, fully namespaced snippet that creates a Model, renders it through a View, and never touches a bare global.
A small namespaced app
window.App = { Models: {}, Views: {} };
App.Models.User = Backbone.Model.extend({ defaults: { name: "" } });
App.Views.User = Backbone.View.extend({
render: function () { this.$el.text(this.model.get("name")); return this; }
});
var user = new App.Models.User({ name: "Grace" });
$("#app").html(new App.Views.User({ model: user }).render().el);
Common pitfalls
Two mistakes show up again and again. The first is recreating the namespace in several files with a plain assignment, which wipes out whatever was there before, so always guard it with window.App = window.App || {}. The second is letting the namespace grow so deep that nobody can remember the path to a class. Keep it shallow, guard the root, and a namespace will carry an app a long way before you need anything heavier.
Frequently Asked Questions
What is namespacing in Backbone.js?
It is the practice of putting your Models, Views, Collections, and Routers under a single application object instead of leaving them as separate globals. One name owns the rest, which prevents collisions and makes structure clear.
How do I create a Backbone namespace?
Define one object, guarded so it is not overwritten, with sub objects for each class type: window.App = window.App || { Models: {}, Views: {}, Collections: {} }. Then attach each class onto it.
Is module loading better than a global namespace?
For larger apps, yes. A loader like RequireJS or native ES modules removes every global, since each file imports what it needs by path. The global object pattern is simpler and fine for small to medium apps.
How deep should a namespace be?
Keep it shallow. Two levels such as App.Models.User handle almost every app. Deep chains are harder to type and maintain, and usually signal that the structure should be flattened.
Read next
Structure your app further:
- Modular Backbone with RequireJS, namespacing without globals
- Organizing Backbone using modules
- What is a Model, the classes you will namespace
Outgrowing a global namespace?
See how modules remove every global and resolve dependencies for you.
Modular Backbone with RequireJS →