HTML5, CSS3, jQuery, JSON, Responsive Design...

bindAll function for ES6 classes

Michael Brown   September 14 2015 05:48:32 AM
I've written a simple JavaScript function to bind multiple methods to an ES6 class's 'this' object.

Problem

The problem is that an ES6/ES2015 class method's context is not autobound to the class's object. This is a particular point of pain for ReactJS when using this syntax. (ReactJS's previous .createClass() syntax did autobind a component's methods to the component's own context.)  So in the code below, the close() and open() methods, which both call this.setState() will fail. This is because those method's this object is not autobound to the component's context, so this.setState() simply doesn't exist.

class ExampleModal extends React.Component {
constructor(props) {
  super(props);
}
close() {
  this.setState({ showModal: false });
}
open(){
  this.setState({ showModal: true });
}


You can bind all the methods manually in the constructor to get around this problem, but that's a massive pain to remember to do that, not to mention a lot of extra lines of code in your constructor.

How To Use es6BindAll

So I wrote the es6BindAll function to do it for you.  Those of you that have used Backbone.js can probably guess that this is inspired by Backbone's bindAll function.

You simply supply the function with the context object as its first parameter, then an array of method names that are to be bound to the object. Note: those methods must exist in the current component/class, i.e. they can't be external functions.
Example use:

import {es6BindAll} from "es6bindall";

class ExampleModal extends React.Component {
constructor(props) {
  super(props);
  es6BindAll(this, ["open", "close"]);
}
close() {
  this.setState({ showModal: false });
}

open(){
  this.setState({ showModal: true });
}



Browser Support

Supports Internet Explorer 9 and upwards, plus all good browsers (i.e. any browser not called Internet Explorer).


Installation

To install via NPM:
npm install es6bindall


Here's links to the packages on npmjs and github:
https://www.npmjs.com/package/es6bindall
https://github.com/brownieboy/es6bindall


Update December 2015

I've subsequently updated es6BindAll so that you can import it as the default, i.e.
import es6BindAll from "es6bindall";

although
import {es6BindAll} from "es6bindall";

will continue to work.

I've also added some proper tests, using Mocha and Chai (I know, like I should have done in the first place!).
 



Comments

1cghgjh  05/06/2017 6:32:27 AM  bindAll function for ES6 classes

Simple one touch game play with lots of levels that will keep you entertained for hours! Jump and fly your way through danger in this rhythm-based action platformer!

{ Link }

About