Created
November 19, 2019 14:26
-
-
Save attaboy/c0b8b820d4c31ddbad759951e8af8032 to your computer and use it in GitHub Desktop.
Simple utility to bind all methods of an instance so that they have `this` context no matter what.
This file contains 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
const blacklist = [ | |
'constructor', | |
'componentDidMount', | |
'componentDidUpdate', | |
'componentWillMount', | |
'componentWillReceiveProps', | |
'componentWillUnmount', | |
'componentWillUpdate', | |
'render', | |
'shouldComponentUpdate' | |
]; | |
function autobind(instance: { [prop: string]: any }) { | |
Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).forEach((propName) => { | |
if (typeof instance[propName] === "function" && !blacklist.includes(propName)) { | |
instance[propName] = instance[propName].bind(instance); | |
} | |
}); | |
} | |
export default autobind; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment