Monday, July 4, 2016

RequireJS For Beginners

First you'll need to download Nodejs and create a simple localhost server. See my blog post on how to do that. You'll need to download a decent text editor for this as well. I recommend Sublime Text which is available for both Windows and Mac OS. You can easily see your directory structure and edit your files in it!


Create the following directory structure:

app\
js\lib\src\

We're going to create a very simple webpage that tells the browser that we're using RequireJS and we'll add a div tag. Call this file index.html and save it in the root directory of your application.

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="NAME"></div>

  </body>
</html>

Every RequireJS application needs a config file. That is what we're telling the web browser via that data-main section. Let's create that config.js file under js/lib/src.

requirejs.config({

baseUrl: 'js/lib/src',
      paths: {
        'jquery': [
             '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
              '../lib/jquery-2.1.1.min'
        ],
        'underscore': 'http://underscorejs.org/underscore',
        'app': '../../../app'
      }
});

// Load the main app module to start the app
requirejs(["app/main"]);

This is telling the browser that we will be using the jquery and underscore javascript libraries reverenced at these URLs. It also tells the browser, when we say "app", reference it off of the app root (that's three directories before the baseUrl and then in the directory app).

The main.js file is the one that calls and references all of the other javascript files. So it tells the web browser that this code requires certain files: the configuration file (shown above) and your script. We'll make a simple script that shows "Hello" followed by a name. Create a file called main.js and put it under the app directory.

require(['config', 'hello'], function(config, hello) {
   hello.showName("NAME", "Bob");
})

This tells the web browser, in the javascript file called hello.js, run the showName function and pass it the parameters "NAME" and "Bob". Let's write that script and save it under js/lib/src.

define(['underscore', 'jquery'], function() {
     var showName = function(div, value) {
        
        value = '<b>Hello ' + value + '!</b> ';
         div = '#' + div;
        $(div).html(value);
       
     };

      return {
           showName: showName
      };

});

This javascript file uses the jquery and underscore javascript files we referenced in the config file. It creates some html text that says "Hello (name)" in bold. This is written in div section. So, looking back at the app.js, we will be writing "Hello Bob!" in the div section NAME (see index.html).

Run your server and view the results.

Okay Now What?

Let's prove to ourselves that we know what we are doing. Let's add a second div in the index.html:

<div id="NAME2"></div>

And add another call in the app.js  file.

hello.showName("NAME2","Mary");

View the file and you should see:
Hello Bob!
Hello Mary!

Now, to show how we would access ANOTHER javascript file, make a copy of hello.js and call it goodbye.js. Change the word "Hello" to "Goodbye". Keep the function name the same. We're going to PROVE that we're using the second script.

Update the app.js file.

require(['config', 'hello', 'goodbye'], function(config, hello, goodbye) {
   hello.showName("NAME", "Bob");
   hello.showName("NAME2", "Mary");
   goodbye.showName("GNAME", "Bob");
   goodbye.showName("GNAME2", "Mary"); })


Now update the index.html file:

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="NAME"></div>
    <div id="NAME2"></div>
    <div id="GNAME"></div>
    <div id="GNAME2"></div>

   </body>
</html>

We we view the page, we will see:

Hello Bob!
Hello Mary!
Goodbye Bob!
Goodbye Mary!

So, there we go, we made a javascript file that referenced two different javascript files!

A Short Fun Project

Let's have some fun with this now. We will make a simple webpage that generates the six stats for an AD&D character: Strength, Dexterity, Constitution, Intelligence, Wisdom and Charisma. We will do a simple 3D6 calculation (roll 3 six-sided dice and add the numbers).

We will update the index.html page as follows:

<html>
  <head>
    <meta charset="utf-8">
    <title>RequireJS</title>
  </head>
  <body>
    <script src="http://requirejs.org/docs/release/2.2.0/comments/require.js" data-main="js/lib/src/config"></script>

    <div id="STR"></div>
    <div id="DEX"></div>
    <div id="CON"></div>
    <div id="INT"></div>
    <div id="WIS"></div>
    <div id="CHA"></div>
   </body>
</html>

Now we will update the main.js to call a different javascript file called character. We'll pass in the name of the stat (which matches the div id in the webpage).

require(['config', 'character'], function(config, character) {
   character.showStat("STR");
   character.showStat("DEX");
   character.showStat("CON");
   character.showStat("INT");
   character.showStat("WIS");
   character.showStat("CHA");
})

We'll create the character.js file and save it under js/lib/src. We'll create a roll function and a showStat function:

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

    var roll = function() {
         return Math.floor(Math.random()*6+1) + Math.floor(Math.random()*6+1) +
            Math.floor(Math.random()*6+1);        
     };

    var showValue = function(div) {
       var value = roll();
       var stat = '<b>' + div + ' </b> ' + value;

       div = '#' + div;
       $(div).html(stat);
    };

     return {
           showValue: showValue,
           getBonus: getBonus,
           roll: roll
     };
});

When we view the page, we will see the stat followed by the value rolled. Refreshing the file will generate a new character.  That's fine, but what if we wanted to use those values somewhere else? We can update the main.js to call the roll function and pass the value to showValue and have showValue use that value:

require(['config', 'character'], function(config, character) {
      var strength = character.roll();
      character.showValue('STR',strength);

      var dexterity = character.roll();
      character.showValue('DEX',dexterity);

      var constitution = character.roll();
      character.showValue('CON',constitution);

      var intelligence = character.roll();
      character.showValue('INT',intelligence);

      var wisdom = character.roll();
      character.showValue('WIS',wisdom);

      var charisma = character.roll();
      character.showValue('CHA',charisma);
})

Then we update the character.js showValue function as follows:

    var showValue = function(div, value) {
       
        var stat = '<b>' + div + ' </b> ' + value;
        div = '#' + div;
        $(div).html(stat);
      
     };

      return {
           showValue: showValue,          
           roll: roll
      };

There you go, a simple AD&D character generator using RequireJS!

No comments:

Post a Comment