Vlad Miller
Vlad Miller

Reputation: 2279

How to properly bind current object context in ES6 using babelify

I'm trying to bind current instance to the class method, please note ES6 syntax.

class SomeClass {

  search() => { ... }

}

Which is 100% legit code, however, babelify doesn't want to compile it

SyntaxError: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js: Unexpected token (50:26) while parsing file: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js\

Instead, now I have to bind context in class constructor

class SomeClass {
  constructor() {
    this.search = this.search.bind(this)
  }
  search() { ... }
}

Which is quite annoying and boring.

UPD: It turns out that this is invalid ES6 syntax; therefore the question is follows. What is the best way to bind instance context to a class method?

UPD2: By default context should be attached, however, the issue with React http://jsbin.com/citafaradu/2/edit?js,console,output

Upvotes: 1

Views: 1161

Answers (1)

Pavlo
Pavlo

Reputation: 44889

This code is not valid ES2015. Prototype methods are defined like this:

class SomeClass {

  search() { /* ... */ }

}

Upvotes: 5

Related Questions