ddkesa
Last Updated: February 25, 2016
·
839
· cell303
A5b4032eaad882492772f4d6d34a9122

autobind for React 0.13 ES6 Components

React 0.13 allows creating React components as ES6 classes. Unfortunately methods do not have this bound to them by default.

Here is a primitive autobind function:

import is from 'is';

function getAllMethods(obj) {
  return Object.getOwnPropertyNames(obj)
    .filter(key => is.fn(obj[key]))
}

function autoBind(obj) {
  getAllMethods(obj.constructor.prototype)
    .forEach(mtd => {
      obj[mtd] = obj[mtd].bind(obj);
    })
}

export default autoBind;

(Use your own implementation to check if a property is a function if you don't use is, e.g. key => typeof obj[key] == 'function')

Usage:

class App extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);
  }
  ...
}
Say Thanks
Respond