Using Require.js

So, last week I covered why we’re using Require.js. Today, let’s look at how to use it. This time I’m just going to go into the two functions that are the heart of Require, then next time I’ll go for how to actually put it into your app.

Require()

require(["some", "dependencies"], function(){Console.log("A function")})
The require function takes two parameters. An array of strings, referencing all of the functions dependencies and a function which is run.

What this does is informs the app that in order to run that function, it must have these dependencies loaded. So it will make sure it has them all available before starting to run the function. The array of strings, which must always be an array even if it’s an array of one, can contain either full file paths or references defined by Require.

References defined by Require, what do you mean? I hear you cry, melodramatically. There are two things this can mean, one is names for file paths that can be defined by your Require config. We’ll cover that tomorrow. The other is functions defined with the define function.

Define()

define("myModule", ["some", "dependencies"], function(){Console.log("A function")})

Define is used to define modules that you intend to call again later. The first parameter is optional and is a single String that is your module’s name, to make it easier to call again later. After that, it looks just like a require function.

So, when do you use which? If you want to run a function but make explicit its dependencies, then use require. If you want to create a module that will be called by another function, then use define.

Tomorrow, putting this into practice.

Advertisements
Tagged , , , ,

One thought on “Using Require.js

  1. […] I’ve Talked about Require and Jasmine and even how to get them to work together. I’ve also talked about the magical […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: