Wednesday, July 13, 2016

Javascript Maps with UnderscoreJS

I'm continuing my discussion about UnderscoreJS, this time focusing on maps. This entry will be brief but hopefully it'll be useful.

I'm presuming that you installed NodeJS and you're familiar with RequireJS. If not, view those blogs that I linked. You'll also need some kind of editor; I recommend Sublime Text which is available for both Windows and Mac OS.

Create the following directory structure:

app\
js\lib\src\

Create this file, call it index.html, and save it in the root directory of your application.

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

    <h1>RequireJS, Underscore, Maps</h1>

    <div id="DISPLAY_MAPx"></div>
    <div id="KEYS"></div>
    <div id="VALUES"></div>
    <div id="SIZE"></div>
    <div id="LAST_NAME"></div>

  </body>
</html>

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"]);


Create a main.js file amd save it under the app directory. This is where we can demonstrate various UnderscoreJS Javascript functions for arrays.

require(['config', 'display'], function(config, display) {

var map = {
"FirstName": "Sandy",
"LastName": "Beach",
"Age": 21
};

    var keys = _.keys(map);
    var values = _.values(map);
    var size = _.size(map);

  var toString = "<br>";
    _.map(map, function(value,keyword){ toString = toString + keyword+":"+value+"<br>"; });

    var lastName = _.propertyOf(map)('LastName');

   display.showName("DISPLAY_MAP", toString);
   display.showName("KEYS", keys);
   display.showName("VALUES", values);
   display.showName("SIZE", size);
   display.showName("LAST_NAME", lastName);

})

Finally, create a file called display.js, and save it under js/lib/src. If you've read my blog on Javascript Arrays, you've seen this before.

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

    return {
           showName: showName
    };

});

Run your server and view the results. Go to the UnderscoreJS page to see all of the other useful functions. Remember: If there is a Javascript package that makes coding easier, use it!

Have fun!

No comments:

Post a Comment