Re-Learning Backbone.js – Require.js (AMD and Shim)

In this post we are going to learn how to use Require.js with Backbone.js and Underscore.js

This post build on the Re-Learning Backbone.js series.

As usual, the examples in this tutorial are extremely simple. We have one goal here and that is to load Underscore.js and Backbone.js using Require.js

We are going to start out with an example that doesn’t function correctly. Don’t worry, I believe it’s important to show you the evolution of creating an application from the very beginning to a working version. We will take very small steps to get where we need to go.

Here are the libraries and their version that we will use in this post:

  • jQuery – version: 1.8.3
  • RequireJS – version: 2.1.2
  • Backbone.js – version: 0.9.9
  • Underscore.js – version 1.4.3

Here’s the source code for the example below: Source

Getting Started

To get started we need a structure for our website such as this:

We also need the following libraries jQuery, Backbone.js, Underscore.js and Require.js. These libraries should be stored in the “libs” directory.

First create two files. The first file will be called Require1.html and this file will be in the root directory. Add the following code to the file.

Here’s the code for Require1.html

All the HTML file does is tell RequireJS to execute the main.js file in the script directory.

The second file will be called main1.js and this file will be in the “scripts” directory. Add the following code to the file.

The main1.js file has two parts, the config method and the require method. The config method is used to setup RequireJs. The config is not mandatory, but it does simplify the code. In the config we included only the “paths” option, but there are many other options available. To see a list of options go to RequireJs Config Options. In the paths option we identify the modules that will be needed. Each module file is in the “scripts/libs” directory. You will notice that each JavaScript file that is referenced does not include the “.js” extension. RequireJS assumes that all files are scripts and the “.js” is not needed. The order of the values in the config paths is not important; the files can be in any order. If we wanted we could have put backbone first.
Continue reading “Re-Learning Backbone.js – Require.js (AMD and Shim)”