Emory Ava Dunbar

Nearly two years as a parent and I feel only marginally better at it. My second daughter was born Monday, October 28th 2013 weighing in at 6 lbs 10 oz and measuring 18.5 inches long.


The difficulty of having children is only outmatched by the fun. I recently read that you get ~940 Saturdays between your child’s birth and their departure for college and I intend to make them count.

Brighton and Emory

Underscore Templates

It has come to my attention that perhaps Underscore templates are a bit misunderstood. Or, perhaps, the community is simply unaware of their best features and usage. Either way, I’d like to provide a primer for the uninitiated and a knowledge base for the rest. The goals and benefits of client side templating have been explored fairly thoroughly so I’ll jump right into the good stuff.

There are lots of code examples below, so make sure to play around with anything you don’t understand. Just head over to underscorejs.org and open up the console.


Based loosely on John Resig’s micro-templating, Underscore templates should have a fairly familiar feel. Put in some text with delimeters for your data, and _.template does the substitution for you, easy peasy.

_.template('<p><%= text %></p>', {text: 'o hai!'});
// <p>o hai!</p>

The syntax is flexible so don’t rage quit if you dislike <%= %>. You can just use different delimiters. Need to HTML escape your data? No problem, just use <%- %>.

_.template('<%- text %>', {text: '1 < 2'});
// 1 &lt; 2

Underscore templates also happen to be logical (as opposed to logic-less), allowing you to use whatever crazy javascript you can come up with. I happen to enjoy this sort of freedom but if it’s not your cup of tea, don’t sweat it.

_.template('<% _.times(5, function(i){ %><%- i %><% }); %>', {});
// 012345

Custom Delimeters

If you’d prefer a different set of delimeters, you can easily provide your own regular expressions for interpolating, escaping, and evaluating. Each regular expression must provide exactly one capturing group.

_.template('{{ wave }}', {wave: 'o/'}, {
  interpolate: /\{\{([\s\S]+?)\}\}/g
// o/

These options can also be set globally via _.templateSettings.


If you leave out the data argument, you are returned a plain old function that you can execute many times over without the overhead of compilation.

var template = _.template('<p><%- text %></p>');
template({text: 'foo'}); // <p>foo</p>
template({text: 'bar'}); // <p>bar</p>

You can inspect the template source via the source property, which is handy for precompiling your templates. It’s crazy fast compared to compiling on each load and, more importantly, it provides useful line/column numbers in stack traces.

_.template('<p><%- text %></p>').source;
// function(obj){
// var __t,__p='',__j=Array.prototype.join,
// print=function(){__p+=__j.call(arguments,'');};
// with(obj||{}){
// __p+='<p>'+
// ((__t=( text ))==null?'':_.escape(__t))+
// '</p>';
// }
// return __p;
// }

While it might seem a bit esoteric, viewing the template source is rather instructive. First and foremost, it proves that templates are just javascript, no magic involved. Secondly, it provides for some interesting techniques.

Slow by Default

Since version 1.3.3, underscore templates have been quite fast. However, backward compatibility concerns force them to be slow by default. By specifying a variable to prefix your data with, you can speed things up by an order of magnitude.

_.template('<%- data.x %>', null, {variable: 'data'});

When a variable is not specified, the template source is wrapped in a with statement. While there are plenty of existing implications regarding the with statement, we’re only concerned with performance here and the with statement makes things much slower.

Template Context

While, in my experience, under-used, a template is always provided with a context, which can be quite useful when rendering your views. This prevents the need to pass a custom data argument to your template, sparing you from memorizing yet another application custom API, not to mention creating another custom API at all. This is maybe my favorite _.template technique but has gone unnoticed by most.

var view = {
  x: 7,
  template: _.template('<b><%- this.x %></b>')
// <b>7</b>

I find it particularly useful in Backbone views but it’s equally useful when rolling your own.

var View = Backbone.View.extend({

  template: _.template(' \
    <h1><%- this.model.get("title") %></h1> \
    <ul><% this.collection.each(function(model) { %> \
      <li><%- model.get("name") %></li> \
    <% }, this); %></ul> \

  render: function() {
    return this;


Further Reading

This post actually turned out relatively small, which I think is a testament to the simplicity of _.template. If you want to dig deeper I’d suggest reading the source, as there really is no substitute. :)

The Doctors Are Leaving

Physicians all over the US are leaving the practice and others are indicating that they soon will, far earlier than they’d otherwise planned.

This is an interesting read on socialism in healthcare highlighting the importance of considering the provider before deciding their prices and choice of patient for them.

As long as becoming a doctor requires years of hard work and dedication, no one will get healthcare for free, regardless of how it’s advertised.


Dave Winer succintly states my feelings on collaborative software development in a quote from Ars Technica.

Eventually you come around to his way of thinking, or he comes around to yours. These are the essential ingredients in good technology. We’re looking for the right answer, not to be proven right, or to prove the other guy wrong.

Looking for the right answer, together.

Side Effects of innerHTML

Today I learned (after a long and arduous debugging session) that innerHTML can have serious side effects when used in Internet Explorer. Consider the following:

var p = document.createElement('p');
p.innerHTML = '<a>test</a>';
a = p.childNodes[0];
p.innerHTML = '';

Here’s a fiddle in case you want to play around with it. In most modern browsers this snippet will happily log 'test' before continuing about it’s business. Internet Explorer, on the other hand, will remove the contents of a when setting p.innerHTML and log the empty string to the console. Obviously this can lead to some interesting results if you’re not expecting it. Hopefully I’ve saved you the debugging time I’ve lost today. ;)

I filed a bug concerning this behavior on the jQuery issue tracker, but it can’t be fixed due to performance considerations (more details in the ticket). That said, working around the issue by using .empty().append(…) is easy to do.


Sundays are for bear suits.

Bear Suit

Brighton Avery Dunbar

It’s official. I’m a father now. My daughter was born on Thursday, December 22nd 2011 weighing in at 7 lbs 6 oz and measuring 19.25 inches long. I’ve never been so happy or exhausted before in my life. My wife was amazing throughout the pregnancy and birth and our family has been incredibly loving and supportive in every way imaginable. Life will never be the same.


echo vs printf

Recently, I caused myself a giant headache because I was uninformed about echo and how it differs from printf (not to mention how it affected my code). Hopefully I can spare you the same pain. For the Software Tools Philosophy to work, one must have a working knowledge of the tools.

Alright, review time. According to man echo, it’s used to “display a line of text”. And so it does! It’s quite handy when you need to dump something to stdout. Especially when that something is literal text.

$ echo cheese and crumpets
cheese and crumpets

I often use echo for this reason, and normally it works in exactly the fashion I expect. However, sometimes what I expect is not reasonable or even logical! I tried to use echo to stitch together a screen stylesheet with a print stylesheet. (I’ve heard that many browser’s download print stylesheets even when they’re not using them. As such, it may as well come in a single http request.) Specifically, I tried to do the following:

echo -n "$(cat screen.css)\n@media print {\n$(cat print.css)\n}\n"

On the surface this looks like a perfectly reasonable approach and, given the correct circumstances, it is. echo dutifully renders the print stylesheet with a wrapping @media declaration. The problem is that the following was included in screen.css:

.clearfix:after, .container:after {
  content:"\0020"; ...

You’ll notice the unicode escape sequence for space (\0200). To echo this looks like an escape sequence (and so it is, just not one we’d like to replace) and so it replaces it. At this point I can hear you saying “But wait! echo has the -E switch for that! It disables interpretation of backslash escape sequences!”. You’re right. It does. It cannot, however, be used granularly. This renders it useless for my task. I need to escape the newlines surrounding the @media declaration, and yet I need to leave the unicode escapes in the stylesheet untouched.

This is where printf saves the day. It works almost identically to the version in stdio.h. It will always replace backslash escapes in the format string and never replace backslash escapes in arguments. In the end, I used the following command:

printf "%s\n@media print {\n%s\n}\n" "$(cat screen.css)" "$(cat print.css)"

This worked like a charm and saved my day. \o/

Hopefully, you’ll remember this next time you start echoing things with escape sequences in them. I have no idea how quotes within the arguments are dealt with but that’s a mystery for another day.

The Redis Manifesto

This excerpt from the redis manifesto is yet another reason to love redis.

Code is like a poem; it’s not just something we write to reach some practical result. Sometimes people that are far from the Redis philosophy suggest using other code written by other authors (frequently in other languages) in order to implement something Redis currently lacks. But to us this is like if Shakespeare decided to end Enrico IV using the Paradiso from the Divina Commedia. Is using any external code a bad idea? Not at all. Like in “One Thousand and One Nights” smaller self contained stories are embedded in a bigger story, we’ll be happy to use beautiful self contained libraries when needed. At the same time, when writing the Redis story we’re trying to write smaller stories that will fit in to other code.

I’m somewhat worried that my productivity will decline because redis doesn’t do the things an RDBMS does but I’m having so much fun that it hardly matters.

Bitwise Not & indexOf

Honestly, I’ve found precious few instances in which I need to use javascript’s bitwise not operator. However, I stumbled across a particularly nice usage of it this morning as I was perusing the express source.

When I use indexOf to check for a substring I often feel the statement is rather clumsy, especially if the variable name is particularly long.

if (someLongVariableName.indexOf(someSubstring) == -1) {
  // do stuff

The == -1 part seems to get lost at the end of the expression and it takes me an extra moment to parse the code. However, I found this brilliant little nugget that makes it much easier to read.

res.contentType = function(type){
  if (!~type.indexOf('.')) type = '.' + type;
  return this.header('Content-Type', mime.type(type));

Taking advantage of the fact that ~(-1) == 0 (and it is the only number with this property), our statement becomes truthy or falsey and we can change our previous example to

if (!~someLongVariableName.indexOf(someSubstring)) {
  // do stuff

Obligatory About Post

Hey! My name is brad. I’m a programmer and I hacked together this site in the hopes that two or three people would eventually check it out. Lately I’ve been thinking to myself

holy cow, node.js is suh-weet! I need to learn more about it post haste and then make a peanut butter sandwich

Strictly speaking, the peanut butter sandwich part is not relevant. It is, however, a good idea and I intend to follow up on it.

node.js is easily the shiniest thing I’ve seen in the past few days, and all the cool kids are doing it so I figured I’d join in the fun. So far I love it although it’s not without a few hurdles. Flow control seemed a bit clumsy at first, but as it turns out there are various libraries that make it much cleaner. I’ll get into details later when I’ve really dug into the platform. I’m also very interested in the v8 engine (and dynamic language engines in general) so I’m going to be making a serious attempt to learn c++ and hack on it.

So if you want to read about javscript, algorithms, computer science or peanut butter sandwiches, this is the place for you. Stop back in sometime soon and I’ll tell you all about them.