WarsawJS Presentation Template

We talk about JavaScript. Each month in Warsaw, Poland.

Make your life easier - use Underscore.js

Adam Miniuk +AdamMiniuk

Can my coding life be easier?

                getElementsByClassName = function(cl) {
                  var retnode = [];
                  var elem = this.getElementsByTagName('*');
                  for (var i = 0; i < elem.length; i++) {
                    if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]);
                  }
                  return retnode;
                }; 
            

You know that!

If you have ever used jQuery

                $('.myClass');
            

What Underscore.js is?

As we can read on the underscorejs.org

It’s the answer to the question:

If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?

How to start?

                <script src="//underscorejs.org/underscore-min.js">
                </script>
                <!--Then we have object called _ -->
            

What's next?

Underscore gives us some functions to use:

                each, map, reduce, reduceRight, find, filter, where, 
                findWhere, reject, every, some, contains, invoke, 
                pluck, max, min, sortBy, groupBy, indexBy, countBy, 
                shuffle, sample, toArray, size, partition
            

These are only collection functions.

Give me some examples!

_.map

                var chairs = [{color: "red", width: 150},
                {color: "green", width: 130}, {color: "white", width: 160}];
                
                _.map(chairs, function(chair) {
                    return chair.color;
                });
                ["red", "green", "white"]
            

_.pluck

                var chairs = [{color: "red", width: 150},
                {color: "green", width: 130},
                {color: "green", width: 130}, {color: "white", width: 160}];
            
                var colors = _.pluck(chairs, "color");
                ["red", "green", "green", "white"]
            

_.uniq

                colors = _.uniq(colors);
                ["green", "red", "white"]
            

_.sortBy

                _.sortBy(colors, "length");
                ["red", "green", "white"]
            

Functional / Object Oriented

Both approaches _.UNDERSCORE_FUNCTION(obj) and _(obj).UNDERSCORE_FUNCTION() are correct

                _.sortBy(_.uniq( _.pluck(chairs, "color")),  "length");
                ["red", "green", "white"]
            

Functional / Object Oriented

                _.chain(chairs)
                .pluck("color")
                .uniq()
                .sortBy("length")
                .value();
                ["red", "green", "white"]
            

Objects

There are so many functions dedicated to object. Let's just try an example.

                var chair = { color: "red", width: 100 };
                _.extend(chair, { color: "green" } );
                { color: "green", width: 100 }
                _.defaults(chair, {color: "white", legs: 4} );
                {color: "green", width: 100, legs: 4}
            

Bind / context

Many of Underscore functions have possibility to bind a context (including each). You can use bind and bindAll to invoke particular method.

                _.bind(function(name) {
                    return name + " chose " + this.color + " chair."
                }, chair, "Adam")();
                "Adam chose green chair."
            

_.template

                var templ = _.template("<h2><%= name %> is clever.</h2>");
                templ({ name: "Adam" });
                <h2>Adam is clever.</h2>
            

_.template is customizable

                _.templateSettings = {
                    evaluate: /<\$([\s\S]+?)\$>/g,
                    interpolate : /{{([\s\S]+?)}}/g,
                    escape      : /<\$-([\s\S]+?)\$>/g
                };
                var templ = _.template("<h2>{{ name }} is clever.</h2>");
                <h2>Adam is clever.</h2>
            

More useful stuff

                _.mixin({ addDay: function (string) {
                    return string + " " + (new Date()).getDay();
                }});
            
                _.addDay("today's day number is");
                "today's day number is 1"
            

Many helpers

Other little useful things

Alternatives?

What about performance? Ask jsPerf!

Thank you!

Fork me on Github