JS Frameworks: Setting up RequireJS

At Viget Labs we have started a class to learn several JavaScript frameworks as a group. To help everyone ramp up on application development, I'm creating a series of posts to walk through the process of building a JavaScript application.

Skip to Screencast ›

I'm a big fan of RequireJS. Writing modules is a great way to keep code organized and prevent unused code from bloating a project. However setting it up for the first time can be a bit overwhelming so I wanted to make a quick write up to go over it.

Why RequireJS? It gives developers a number of useful tools for handling some things related to developing Backbone apps that the library doesn't provide out of the box. I'll be using it for dependency management, JavaScript templates, and to tuck some other common behavior under the hood.

 1 // For this example usage, the first argument dictates
 2 // requirements for this module, the second argument tells
 3 // requirejs how to define this module after it has loaded
 4 // all dependencies.
 5 define([
 6   'models/widget', 
 7   // The "!" tells requirejs to use a module as a plugin. 
 8   // In a later post, I'll go over this in detail
 9   'template!templates/widget_factory'
10   // Notice how our modules become arguments in a 
11   // callback function?
12 ], function(WidgetModel, template) {
13   
14   // Define our module....
15   var WidgetFactory = Backbone.View.extend({
16 
17     template: template
18 
19     // This function runs every time we make a new WidgetFactory
20     initialize: function() {
21       this.model = new WidgetModel();
22       this.render();
23     },
24 
25     // The function typically reserved for generating HTML
26     // for a Backbone.View
27     render: function() {
28       var markup = this.template( this.model.toJSON() );
29       this.$el.html(markup);
30     }
31 
32   });
33 
34   // Now that we've defined it, return the value so that other 
35   // modules can use this one!
36   return WidgetFactory;
37 
38 });

It isn't essential at this point that you understand everything going on in the above code sample. Just remember that as your application becomes more complicated, using a system like RequireJS helps to keep things organized and prevents the need for long namespaces that can clutter things up.

Let's begin!

Screencast:

I've also tagged the final result on GitHub.