Created
August 29, 2016 11:54
-
-
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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