I’ve recently started to include undescore.js library to all JavaScript applications and sites I create. Underscore is a small library providing “a lot of the functional programming support that you would expect in Prototype.js (or Ruby)”. I originally found this library when using Backbone.js framework.
Underscore provides about 60 functions, but there are two that I’ve found especially useful.
1. bindAll
I’ve never really understood JavaScript’s this-context and why it’s implemented so oddly. When binding object’s method as an event handler, object context is lost making this-keyword fairly useless.
But hopefully we have Underscore and bindAll. It binds a number of methods on the object to be run in the context of that object whenever they are invoked.
See this example stoled directly from documentation:
var buttonView = {
label : 'underscore',
onClick : function(){ alert('clicked: ' + this.label); },
onHover : function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView);
jQuery('#underscore_button').bind('click', buttonView.onClick);
=> When the button is clicked, this.label will have the correct value...
2. Templates
I found myself writing a code like this:
var html = "<h1>Menu</h1><ul><li>"+item1+"</li><li>"+item2+"</li></ul>"
Which is… wrong. You should never mix functional code and presentation. Underscore has a simple template function, which allows you to separate markup from JavaScript.
You can define template on your html-source:
<script id="my-template" type="javascript/template">
<h1>Menu</h1>
<li><%= item1 %></li>
<li><%= item2 %></li>
</script>
And then render it on JavaScript side:
var template = _.template(jQuery("#my-template").html());
var html = template({ item1: item1, item2: item2 });
No more messy html within JavaScript!
With these two simple functions my life gets much easier






