Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Created August 29, 2016 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlpokus/af6262b1cc1312fa3494d57c7ec25883 to your computer and use it in GitHub Desktop.
Save karlpokus/af6262b1cc1312fa3494d57c7ec25883 to your computer and use it in GitHub Desktop.
Pass 1+ objects to bind all functions to it - creating a useful <this>
// Problem: Callbacks are called with the window object as <this>
// Solution: Bind all functions to their object
// An implementation of http://underscorejs.org/#bindAll
// Demo -> http://codepen.io/KarlPokus/pen/Lkwqyj
function bindAll(x) {
var wat = Object.prototype.toString;
if (wat.call(x) === '[object Object]') {
x = [x];
}
if (wat.call(x) === '[object Array]') {
x.forEach(function(o){
for (var k in o) {
if (typeof o[k] === 'function' && o.hasOwnProperty(k)) {
o[k] = o[k].bind(o); // No need to return anything. Objects are passed by reference
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment