Get into RequireJS

Intro

Hi all, welcome to Get Into RequireJS! If you have good skills on javascript and already knows about the Revealing Module Pattern, get ready because, I will go cut to the chase!

What is RequireJS?

RequireJS is a module loader. Its functionality is to load modules and take care of dependencies for you. When you define a module, you will identify its dependencies and RequireJS will load those dependencies in runtime and just when they are needed!

How to add RequireJS to the project?

RequireJs assumes that you have a specifc directory structure in your project. Of course you can override this settings, but for the demonstration I will follow the default structure, which is the following:

project-directory/

  • project.html
  • scripts/

Under the scripts folder, you will have all the javascript for your project. I always suggest to have the third party libraries separated from your files, so, in my demo I have the following structure:

project-directory/

  • blog.html
  • scripts/
    • app/
    • lib/
    • main.js

Where my code goes to app folder and third party goes to the lib folder.

In the html page you will just include the RequireJS:


<script data-main="scripts/main" src="scripts/lib/require.js"></script>

The data-main attribute, indicates to RequireJS, that once it is loaded, it will have to load the scripts/main.js file. There are other ways to do this, but this one, without any configuration, is definitely the simplest one. Note that I did not refer main.js but only main, this is because RequireJS expects to load only javascript files, so you can omit the extension when you refer your modules.

On the main.js, normally I have some RequireJS configuration and the first call to my application API:


// requirejs configuration

// Define baseUrl (the base folder for the js files)

// Define path to jQuery

requirejs.config({

  baseUrl: 'scripts',

  paths: {

    jquery: 'lib/jquery'

  }

});

// Start the main app logic.

requirejs(['app/blog'],

  function (blog) {

    blog.start();

  });

In the code to start the application, I am saying to RequireJS that I need the module blog and then I can call my function that starts the application. We will just see how that works.

How to define a module?

The structure of a RequireJs module, follows the Module Pattern

In my demo I have the following module (file app/blog.js):


define(['app/dataservice', 'app/presenter'], function(dataservice, presenter){

  var start = function(){

    dataservice.getPosts(presenter.renderPosts);

  };

  return {

    start: start

  }

})

The code indicates that the module blog, depends on dataservice and presenter modules. On the start function, I am calling getPosts on dataservice module and I am passing the renderPosts on the presenter module as callback (not the best way, but for demo purpose is fine).

Picking one of the dependencies modules, for instance the dataservice, it is very similar as it also follows the same structure:


define(['jquery'],function($){

  var getPosts = function(callback){

  $.get('data/posts.json',callback)

  };

  return {

    getPosts: getPosts

  }

})

Final notes

There are a lot of configuration that you can do, different ways to load modules but, this was a cut to the chase, just to show how easy is to use RequireJS. If you thought it was interesting and want to start using it, I suggest to take a look at the documentation first.

You can download my complete demo in Github.

preview

Advertisements

Javascript Revealing Module Pattern

On a previous post  I refer the javascript Revealing Module Pattern, in this post I want to explain how it works and how can it help you to structure your javascript code. 

First lets look to its structure:

var Calculator = function() {
  // code goes here
}();

The code starts with a definition of a variable, which we associate a function that is invoked as soon as as the script loads (this is done with the “()” at the end).

Your variables and functions should go inside of the Calculator in the “code goes here” part.

Now, one of the most interesting parts, inside the Calculator we can declare private and public members. For the private members we just have to declare them inside of the Calculator and, for the public members, we have to add a return statement and declare the public members inside it.

Lets look at the structure of the complete Revealing Module Pattern:

var calculator = function() {
  // private members goes here
  // ...
  // public members goes here
  return{
    // ...
  };
}();

And now lets look at the implementation of the Calculator that just adds and subtracts 2 numbers and logs the result to the console if configured that way:

var Calculator = function() {
  // private members goes here
  var privateLog = false;
  var privateConfig = function(shouldLog) {
    privateLog = shouldLog;
  };
  var privateAdd = function (x,y) {
    var result = x + y;
    if (privateLog) {
      console.log(result);
    }
    return result;
  };
  var privateSubtract = function (x,y) {
    var result = x - y;
    if (privateLog) {
      console.log(result);
    }
    return result;
  };
  // public members goes here
  return{
    publicConfig: privateConfig,
    publicAdd: privateAdd,
    publicSubtract: privateSubtract
  };
}();

Calculator.publicConfig(true); // configures Calculator to log to console
Calculator.publicAdd(1,2); // logs 3
Calculator.publicSubtract(2,1); // logs 1

Analyzing the code for the Calculator, you can see that all public members are exposed in the object literal that is returned when the Calculator is invoked. All the other members are private and cannot be accessed outside of the Calculator.

The Revealing Module Pattern is one of my favorites design patterns to structure my javascript code because it is easy to implement, easy to read (which is good for maintenance) and for the capability to declare private and public members.

You can see this code in this jsFiddle.