[null, {"document_url": "https://auth0.com/blog/backbonejs-getting-started/", "unformatted_src": "https://cdn.auth0.com/blog/backbone/gettingstarted.png", "src": "https://cdn.auth0.com/blog/backbone/gettingstarted.png", "formatted_filename": "gettingstarted", "alt_text": "BackboneJS: Getting Started"}, null, null, null, null, null, {"document_url": "https://auth0.com/blog/backbonejs-getting-started/", "unformatted_src": "https://cdn2.auth0.com/docs/media/articles/web/hosted-login.png", "src": "https://cdn2.auth0.com/docs/media/articles/web/hosted-login.png", "formatted_filename": "hosted login", "alt_text": "Auth0 Login Page"}, null, null, null, null, {"document_url": "https://auth0.com/blog/backbonejs-getting-started/", "unformatted_src": "https://cdn.auth0.com/blog/guest-authors/pencil.png", "src": "https://cdn.auth0.com/blog/guest-authors/pencil.png", "formatted_filename": "pencil", "alt_text": "Auth0 Guest Author Program"}, null]
BackboneJS: Getting Started

Learn how to quickly build apps with BackboneJS. 
TL;DR: BackboneJS is a JavaScript library that provides models with key-value bindings and custom events, views with declarative event handling, and collections with an abundant API of enumerable functions. Currently, BackboneJS has over 25,000 stars on GitHub. BackboneJS gives your web applications structure. In this tutorial, I'll show you how to build a web application with BackboneJS and add authentication to it. Check out the repo to get the code.

BackboneJS is a JavaScript library, built by Jeremy Ashkenas and maintained by a team of contributors. It is an open source component of DocumentCloud. It was initially released in 2010. Since then, it has undergone tremendous growth and adoption in the developer community. Over the past 2 years, the use of Backbone have declined due to new libraries and framework like ReactJS, Vue.js and Angular. The latest stable release is 1.3.3 and it was tagged on April 5, 2016. Actively used open source projects and libraries tag releases very often, which signifies growth. However, BackboneJS has been stagnant for over a year now!

Furthermore, there are many web platforms that use BackboneJS to build their frontends. Such platforms include Trello, Bitbucket, Foursquare, SeatGeek and more. The documentation is very comrehensive.

Understanding Key Concepts in BackboneJS

BackboneJS has a philosophy: Keep Business logic separate from User Interface. When the two are entangled, change is hard. The key concepts needed to understand how BackboneJS works are:

I'll give a basic overview of these concepts to nourish your understanding of BackboneJS.


A Model is a layer that transforms and syncs data with a persistence layer (mostly RESTful API interacting with a database). They contain all the helpful functions needed to manipulate some piece of data from the persistence layer. When any of its data is modified, Models trigger change events.

Consider a Model as a sort of manipulator. Instead of directly interacting with the data from your API, it serves as a layer that allows you easily manipulate every tiny piece of data in a very friendly and fantastic way.

Here's a simple case study: Imagine we are in charge of a gift shop and we need to build a database of the gifts that we sell. We need to keep track of the stock of those gifts. Details like the price, brand, stock and type.

Now, we can create an instance of the Shop model and populate it like so:

We can also add default attributes to the Model like below:

Now, we can call get and set methods on an instance of the Shop model. If we want to fetch the brand of the gift, we will retrieve it with this:

Let's look at another practical case. If we need to create a new user on the backend, we can instantiate a new User Model and call the save method.

We can fetch the details of a user that has been created with an id with the code below:

Updating the User Model will look like this:


Collections are ordered sets of models. You can bind some events to be notified when any model in the collection has been modified. Events such as change, add, remove.

Let's create a Backbone collection and add models to it.

Now, we can set the Shop model to our collection like this:

The next thing will be to instantiate the Collection and the instances of our models like this:

To access the models in the collection, you can use each, one of the Underscore methods available to loop over the collection and present the data to the screen. During the iteration, you can perform model methods like get/set on each model.

Other popular methods you can use on a collection are toJSON, and sync.


Backbone views can be used with any JavaScript templating library. It is unopinionated about the process used to render View objects and their subviews into UI. The views handle user input and interactivity, renders data from the model and also sends captureed input back to the model.

The views listen to the model "change" events, and react or re-render themselves appropriately.

Note: Templates allow us to render the User Interface as an alternative to direct DOM manipulation.

Now, let's use a template


Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events.

In the code above, we copied all of Backbone's events to a JavaScript object using the extend functionality of underscore. So we listen on alert Backbone event and then trigger the event.

Let's try something more practical. Say we have a UserModel,

In the code above, the user model will now listen to change events on itself. Once you set the name to another value, it triggers the change event that calls the someChange function.

In Backbone, you can also listen to just a specific attribute change. For example, we can listen to only title attribute change. How? We simply chain it with a colon like so: change:title.

The change event is only triggered whenever the title changes. And then calls the someChange function.

We also have built-in events that occur on collections. Check out the catalog of built-in Backbone events.

Our app: Address Book

The app we will build today is an Address Book. This app simply manages the address of employees in an organization. We won't make use of any back-end, but will take advantage of Backbone Collections. I'll leave you to persist it to a backend or use local Storage.

Build The App With BackBoneJS

We'll need three main dependencies, backbone.js, underscore and jquery. Go ahead and create your app directory.

In the root directory, create an index.html file. Also create css, and js folders within the directory.

Inside the js directory, go ahead and create the collections, models and views directories.

Populate the index.html file with the following code:

Let's analyze the code above. We have three template-type scripts. One for displaying the list of employees, another for editing and creating new employees and one for displaying the link for creating new employees.

Furthermore, we referenced jquery, underscore and backbone libraries. We also linked some views and script files that do not exist yet. We'll create them soon.

Finally, there is a startup function, EmployeeManager.start(), that takes in an array of employees for display when the app is started. You'll understand how this works in a couple of minutes.

Next, open up the models directory and create an employee.js file.


We just set the defaults of our model attributes to null. In our app, we are not persisting anything so our model will be very simple.

Next, create an employees.js file in the collections directory and add the following code to it:


EmployeeManager.Views.Employee = Backbone.View.extend({ tagName: 'li', className: 'media col-md-6 col-lg-4', template: _.template($('#tpl-contact').html()),

events: { 'click .delete-employee': 'onClickDelete' },

initialize: function() { this.listenTo(this.model, 'remove', this.remove); },

render: function() { var html = this.template(this.model.toJSON()); this.$el.append(html); return this; },

onClickDelete: function(e) { e.preventDefault(); this.model.collection.remove(this.model); } }); ```

This is the view that handles the details of each employee. In the code above, we have the html tag, <li> that is assigned a class. This is the element that houses the employee detail. The render function ensures that the right data is appended to the template and displays on the page. The onClickDelete function is for removing the data from the model and collection.

The events object simply maps the onClickDelete function to the click event of the delete-employee button.

Next, create the add employee form view. Create a file, employeeForm.js in the js/views directory.


In the code above, the onFormSubmit function is called when we submit the form. And this function is called whenever the submit event is fired. The render function assigns the model to the template.

Finally, create a file, employees.js in the js/views directory.


This view is responsible for the list of employees on the page.

Create The Router

This is a single page application, we need to make use of some routing capabilities. In the js directory, create a router.js file and add the code below:


In the code above, whenever each of the routes on the left are visited, the name of the actions on the right are fired as events, so the router can listen on it like:

Create The App Logic

Let's go ahead and create the js/app.js file. This is the file that houses the functionalities that happens whenever each route is visited. Add the code below to it:

Remember the EmployeeManager.start() function that was called in the index.html file? The function houses the events that the router listens on.

Backbone.history.start() is used to allow the use of hashbangs for the routes.

Run Your App

Now, launch your app. It should start up like so: Launching the app Creating a new employee Editing an employee details
 




BackboneJS is a library that can be used to build your user interfaces. Right now, it has not undergone updates in over a year. And many web applications that initially used it heavily have either moved away to new JS libraries or are currently rewriting their frontend to make use of another tool.

 EmberJS Authentication Tutorial
