Skip to content

Instantly share code, notes, and snippets.

@attaboy
Created November 19, 2019 14:26
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 attaboy/c0b8b820d4c31ddbad759951e8af8032 to your computer and use it in GitHub Desktop.
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.
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