In this chapter we will be going over how to download our sample project and setup a development environment so you can get started writing code. If you're already comfortable with git, jQuery, Underscore.js, and debugging JavaScript in the browser, you may want to skip parts of this chapter.
When building a reasonably complex site, you will be spending most of your time in a code editor, so it's important you find one that works well for you. Some developers like a full-fledged IDE like WebStorm, while others use a lighter-weight GUI like Sublime Text or Textmate, and yet others stick to a terminal-based editor like Vim or Emacs. We promise, though, that Notepad/TextEdit won't cut it, and we do recommend you choose an editor that works for you.
In case you are interested: authors Aidan and Casey use Sublime Text, Phil and Tim use Vim and Dave uses IntelliJ.
Over the course of this book, we're going to walk you through building a sample one-page application with Backbone, called "Hubbub." The project is an organizer for GitHub issues, known to some as a Kanban board. The basic functionalty is this: you can search for code repositories hosted on GitHub (either owned by you or someone else), add them to your board, then categorize each issue as "ToDo", "In Progress" or "Done". You can check out the finished product here.
Let's get you set up. If you are familiar with all the topics in this chapter, feel free to jump to Chapter 2: Test Driven Development.
Depending upon your development background, you may or may not have used a version control system. They are helpful for individuals to keep track of changes within their project over time, and they become essential when working in a team environment. Git is currently the most popular version control system, and that's what we'll be using throughout the Hubbub project.
GitHub is a site to host and share Git repos. Before we even started writing the book, we built Hubbub collaboratively, but remotely, by saving our changes in Git and synchronizing them through GitHub (which allowed us to keep track of the changes over time). Git has a feature called "branches," which allows you to have the same project in multiple contexts at once. We have a working version of the application in the complete branch, but we created a separate version (as the boilerplate branch) that includes just the basics you need to build Hubbub from scratch.
To get your own personal copy ("fork") of the Hubbub project:
Next, install Git. While you'll eventually want to get comfortable with Git on the command line--and here's a great interactive tutorial for doing so --using GitHub's desktop application provides a nice GUI that masks a lot of the nitty-gritty. Use whichever you feel comfortable with. Let's get the Hubbub project onto your computer:
Command Line | GitHub Desktop | |
---|---|---|
Install | Official Installers | Mac or Windows |
Clone Hubbub (make sure to replace your GitHub USERNAME) | git clone cd hubbub |
Near the top left of your Hubbub fork page (https://github.com/ USERNAME/hubbub), click (or Windows). After choosing a folder to save the project in, you'll now have "Hubbub" listed under "My Repositories". |
Create your "master" branch | git checkout -b master |
On the "Branches" tab, click the "+" next to "boilerplate". Name that branch "master". |
Push your new branch up to GitHub | git push -u origin master |
Next to your new "master" branch, click "Publish." |
The internals of Git are complex, but when you're working on a project by yourself on a single computer, there are really only a few commands you need to know. Inside the project folder, you'll see a README.md file. Open that up in your editor. Add your name just below the title:
Hubbub ====== by SO-AND-SO.
Every time you make a standalone modification to one or more files, you want to "commit" those changes to say that you've accomplished that step.
Command Line | GitHub Desktop | ||
---|---|---|---|
View what's been changed | git status |
Open the "Changes" tab. | |
Commit the changes | git add . git commit -am "added my name to the README" git status |
Type "added my name to the README" in the "Commit summary" field and press "Commit." | Use descriptive commit messages to make your repo history easy to follow. |
Send the changes to GitHub | git push | Click "Sync" |
Open the index.html file at the base of the Hubbub project directory. This acts as the skeleton for our one-page application. We include a simple stylesheet (which includes Twitter Bootstrap) in the <head>, just to provide a baseline of styling.
Backbone has two dependencies: jQuery for doing DOM manipulation, and Underscore for utility functions. We will discuss each in a moment.
NOTE: Backbone also accepts a couple of alternatives for it's dependencies. Zepto can be used in place of jQuery, which drops support for older browsers in exchange for a much smaller filesize. Lo-Dash is a fully-compatible replacement for Underscore that emphasizes performance and customizability. If you want to support old browsers (e.g. Internet Explorer 6), you should also include json2.js.
We also included marked.js, which we will use to parse the Markdown content of GitHub Issues. You'll notice that <body> is fairly empty, and it will remain that way, because we'll use JavaScript (via Backbone and templates) to create the markup. More about that is covered in Chapter 4: Views.
jQuery is the most popular library in use today, in JavaScript or otherwise. jQuery normalizes browser inconsistencies for common operations like accessing elements in the DOM, doing requests to a server via AJAX, crafting animations, and so on. For example:
// when they hover over the menu button
$('.menuButton').hover(function(){
// slide the menu down while fading it in
$('.menu').slideDown('fast').fadeIn('slow');
});
At their simplest, jQuery DOM operations consist of a selector passed to the $() - a.k.a. jQuery() - function, with one or more method calls chained together after it. Running the $() function with a selector returns a jQuery object, which refers to a set of zero or more elements on the page. If you save this object to a variable, it's a common convention to prefix that variable name with a dollar-sign:
var $currentItem = $('.navBar .current');
$currentItem.hide();
jQuery is used throughout the Backbone.View
class internally, and we will be using it directly later in Chapter 4: Views.
Jeremy Ashkenas created Backbone when he was part of DocumentCloud, but he also wrote a more general-purpose "utility-belt library" called Underscore, which Backbone depends upon. Underscore is meant to provide functions that are commonly used in JavaScript applications. If you're coming from another programming language, you can think of Underscore as the "standard library" JavaScript never had. Some methods like _.each() and _.size() normalize methods available between Arrays, Arguments and Objects, while providing a "shim" in some places where the method is only natively available in newer browsers:
var lastNames = _.pluck([
{first: 'Arnold', last: 'Schwarzenegger'},
{first: 'Wesley', last: 'Snipes'},
{first: 'Sylvester', last: 'Stallone'}
], 'last');
// find the longest last name
_.max(lastNames, function
return lastName.length;
});
=> 'Schwarzenegger'
Others like _.debounce() come in handy for doing more complex time-based operations:
var $button = $('.myButton');
// wait 100ms after they stop clicking
$button.on('click', _.debounce(function () {
console.log('Ok ok, we get it...');
}, 100));
// simulate a trigger-happy user
$button.click().click().click();
Take some time to look through the documentation at what is included. If you're feeling really ambitious, you can also check out the well-annotated source code.
While we know you use a web browser all the time, doing serious client-side development requires a deep understanding of the browser as both a platform and a tool. We highly recommend using Google Chrome or Mozilla Firefox, as they have the strongest developer tools. Open up the completed Hubbub site, then fire up the developer tools:
Chrome | Firebug | Tips | |
---|---|---|---|
Install the developer tools | (preinstalled) | Install Firebug | |
Open them up | Click the Chrome menu () on the far right end of the toolbar. Under Tools, click Developer Tools. | Click the Firebug button () at the far right of your toolbar. | |
See all of the downloaded assets | Click the Network tab, then refresh the page. | Click the Net tab, then refresh the page. | It's useful to check if a particular file is being loaded, how big it is, etc. Click an individual row to get more details. |
Inspect the DOM | Click the Elements tab. | Click the HTML tab. | This view allows you to see the rendered markup, and selecting an element allows you to play with the CSS and see the changes live. |
Open the primary JavaScript file | Click the Sources tab, then click the tiny arrow icon () in the top left and select index.js . |
Click the Script tab, then the dropdown on the left of the secondary bar of the debugger, and select index.js . |
While many JavaScript developers simply use console.log() to debug, being able to stop execution of the code and inspect the state of your application is very useful. To start, click the line number next to Backbone.History.start() to set a breakpoint. You will see a marker appear on (or next to) the number. Refresh the page, and you should see that line highlighted. This means the page has been paused, and this line is about to run.
You can hover over variables to see their values, and jump around the Call Stack ("Stack" in Firebug) by clicking the different function names in the right sidebar. (A "call stack" is a list of what methods have been executed to lead to the current line. You can think of these as JavaScript "breadcrumbs.")
Chrome | Firebug | ||
---|---|---|---|
Continue | Resume execution of the code, until it hits the next breakpoint, or indefinitely | ||
Step Into | If the current line has a function call, jump into that function | ||
Step Over | If the current line has a function call, execute it and stop on the next line | ||
Step Out | Finish execution of the current function, and stop when it returns to the calling function |
Lastly, the Console tab allows you to execute arbitrary JavaScript on the page, and if you're paused in the debugger, it executes in the current context. Try some jQuery:
$('body').css('background-color', 'yellow');
The Console will also display any JavaScript errors that occur in the page, so it's useful to keep this window open during development.
Now that we've introduced the projects, tools and libraries you'll be using, let's get into some specifics about Backbone.
There has been error in communication with Booktype server. Not sure right now where is the problem.
You should refresh this page.