Learning Backbone.js Chapter 1: A Quick Overview
I’ve found it difficult to find a guide for learning Backbone.js. They’re probably out there — but it isn’t easy. This is the first in a series of articles dedicated to giving a complete overview of Backbone.js through simple examples and concise code.
Something of a cookbook, you might say.
What you’ll need:
- Underscore.js: A required library for Backbone, it also adds over 60 functions for making Javascript development easier.
- Backbone.js: The meat of it. This is what we will use for all the magic.
What we’re making
Today we’ll make a map which displays tweets via the Google Maps API and twitter search results (For the sake of simplicity, we won’t go in to the Twitter API yet). We’ll focus on fundamental construction using the Model, Collection and View components of Backbone.
The twitter map shows tweets around the world.
Hopefully, by the end of this you will have a beautiful night sky lit up by tweets around North America. Let’s get started!
A brief introduction:
Backbone.js is used to “supply structure to Javascript-heavy applications”1. It separates logic into Models, Views, Collections, and Routers.
The architecture of Backbone.js
A typical Backbone application will use models to keep track of information, assisted by collections (groups of data). Views help display this information, by binding themselves to changes in data. Routers help orchestrate all of this by providing the ability to navigate to various parts of an application seamlessly.
Backbone is Model Driven
At the core of all Backbone applications are models. Models, as you may have guessed, act as the base level of information. Since the purpose of our application is to display tweets, let’s create a model to define them here:
What just happened? First we created duplicate of the Backbone Model object. Next we instantiated it as a new Tweet within the myTweet variable.
Pretty simple. But let’s say we don’t want a carbon copy of the Backbone model? Perhaps we need to add custom methods to our model, or we want to define the same defaults for every instance of the Tweet model. Let’s create a new model which extends the base Backbone.Model object:
I threw in another function here, .toJSON(). For models, this will return a JSON representation of the model’s attributes. When used on collections, it will return an Array of JSON objects for each model it contains.
Working with Collections.
The Tweet model will work well for this application, however we’ll need to keep track of more than one of them. This is where collections come in to play. Collections are designed to create, delete, and manage groups of models. Let’s create one here:
Noticing a trend? Here we first create a Tweet model. Then we create the TweetsCollection collection which references this model. Finally, we use the add method of collections to create a new Tweet within with the collection.
Backbone objects have events
In addition to this, all backbone objects can respond to events. Say, for example, you wish to perform an action every time a new record is added to a collection. Consider the following:
Pretty simple huh? Backbone events are powerful, I would recommend doing some reading on what events are available to models and collections. There are some really neat things you can do with them.
Pulling it all Together
Now that we’ve established some form of a basic understanding, let’s get in to the application! First we need some initial construction:
Cool. Now in your js folder, add a file called “map.js”. We’ll add all of the backbone code into here. From this point on we’ll pick up quite a bit of speed, but I’ll be sure to comment on everything new along the way.
Let’s recycle some of the code made earlier, with some additions:
Overall not too bad, but there are some new elements here. url, fetch, parse, and initialize.
- url: Backbone is designed enable easy access to information on a server. When we set the
urlproperty, we tell the collection where it can find information. - fetch: Once a url has been established,
fetchcan be used to retrieve new information. In this case, we will request a json object from the Twitter search service. - parse: A handy function. Whenever the
fetchevent is fired, parse enables you to preprocess data before it is stored in the collection. In example above, we use the underscore method_.filter()2 to prevent any tweets that do not have a specific geolocation from being stored. - initialize: A staple of Backbone. Initialize is a method of each backbone object which will always run upon instantiation (in this case, the collection). Here we tell it to fetch new information from the server at an interval of 2 seconds.
Using Views
In order to display these tweets, we’ll need to create a view for the map. As said earlier, views are the presentational element associated with Backbone; we’ll use them to display content from our collection. I think views are best taught through example, so let’s jump right in to it. Take a close look at the preceding code and add it right after your model and collection code
A lot going on there, right? Let’s take a look at everything going on.
- Line 10: The
elproperty is used to describe the html element associated with a view. In this case, we select the #map_canvas div tag. - Lines 14-31: Standard Google Maps API stuff. This is where the map gets generated. Note that we set the height of the map_canvas to the height of the window to make sure the map is the correct size.
- Lines 36-51: Here we add an event to add a tweet to the map every time the collection associated with this view adds a new record.
UPDATE : Newer versions of Backbone will actively make a distinction
between el and $el. Use el to access the raw HTML DOM object.
Use $el to access the jQuery version, for example:
// Without jQuery:
this.el.text = "Hello world";
// Use jQuery:
this.$el.text("I'm using jQuery!");
Initialize!
Finally, we instantiate the tweets collection and map view, setting everything in motion:
Cool, a TwitterMap.
Pop open the browser and take a look at your freshly created TwitterMap! We could use the Twitter API to make the tweets appear at an exceptionally faster rate. However you really can’t beat the simplicity of the basic search.
Conclusion
I’m not the first person to write a tutorial on backbone to say “But we’ve only scratched the surface”, and I certainly won’t be the last. Future installments will delve into a more detailed overview of how models and collections work. We’ll go through events, syncing information, and other important concepts. I look forward to showing you what can be done within Backbone!