Last Updated: February 25, 2016
· camachgk

_.deepBindAll for Underscore.js

Underscore has a great method called _.bindAll ( that ensures all methods on an object are always run within the context of that object whenever they are invoked.

Recently, I found a need for a more robust _.bindAll that would recursively look for all the methods on the object and it's child objects. This little method is the result:

((_) ->
  _.deepBindAll = (obj) ->
    target = _.last arguments
    _.each obj, (value, key) ->
      if _.isFunction value
        obj[key] = _.bind value, target
      else if _.isObject value
        obj[key] = _.deepBindAll value, target

Now, deep referenced methods get the same treatment as if they were defined directly on the parent:

foo = 
  bar : 'test' 
  x :
    y : ->
  z : ->

_.deepBindAll foo
foo.x.y() is foo.z() is 'test' # true