Thursday, July 30, 2015

What does _.bind() do?

The name, "bind", conjures fear.  It's scary.  Binding sounds mysterious and strange.

Underscore.js has the _.bind() function.  What does it do?

Let's say that you using the JavaScript setTimeout() function to set the focus on a jQuery DOM element.

var el = $('#myinput');
setTimeout(function() { el.focus(); }, 50);

The setTimeout() function takes a standalone function as its first argument.

Now, consider this code:

var el = $('#myinput');
setTimeout(el.focus, 50);

This code doesn't work.  Why?  Well, the focus() call is an object method, not a standalone function.  The setTimeout() function expects a standalone function, not an object method.

A standalone function and an object method aren't the same thing.  If you pass an object method as an argument that expects a standalone function, it's not the same thing, it's wrong and it doesn't work.

It's as if you passed a string as an argument to a function that expects a number.  You passed the wrong kind of thing, even if the string contains a number.  If you want it to work, you have to convert the string to the proper type before calling the function.

So, how can you convert an object method call into a standalone function?

One way is to create a standalone function that calls the object method as you did in the original code.

A second way is to call the _.bind() function.

The _.bind() function says, "Create a standalone function that invokes the method in the first argument, using the second argument as the this object."

So, instead of creating your own standalone function, the _.bind() function will create one for you.

var el = $('#myinput');
setTimeout(_.bind(el.focus, el), 50);

The _.bind(el.focus, el) code creates a standalone function that calls the el.focus() method.  You can think of it as converting a method (call) into a standalone function.

The _.bind() implementation is more complex but you can understand it by imagining that it is implemented like this:

function bind(method, self) {
  return function() {
    self.method(); // this doesn't work; it's just for clarity

That's what _bind.() does.  It takes a method call and "converts" it into a standalone function.

Once you grasp this, you will discover that _.bind() has additional uses, such as converting a standalone function call with multiple arguments into a standalone function with no arguments.

With this explanation, I hope that _.bind() and binding is no longer mysterious and strange.  And not scary.


  1. This comment has been removed by a blog administrator.

  2. This comment has been removed by a blog administrator.