https://github.com/posrix/es6-class-bind-all
Automaticlly bind 'this' scope of all methods in es6 class
https://github.com/posrix/es6-class-bind-all
bind class es6 scope this
Last synced: 12 months ago
JSON representation
Automaticlly bind 'this' scope of all methods in es6 class
- Host: GitHub
- URL: https://github.com/posrix/es6-class-bind-all
- Owner: posrix
- License: mit
- Created: 2017-07-23T08:28:18.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-07-02T07:21:23.000Z (over 7 years ago)
- Last Synced: 2025-02-04T03:46:44.651Z (about 1 year ago)
- Topics: bind, class, es6, scope, this
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/es6-class-bind-all
- Size: 6.84 KB
- Stars: 11
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
## Problem
As you see, too many `.bind()` operations in constructor. Once you have tons of classes
are called in callback or whatever something change it's scope, it will be horribly troublesome.
```js
class Person {
constructor() {
this.name = 'Steve'
this.age = 20
this.gender = 'male'
this.setName = this.setName.bind(this)
this.setAge = this.setAge.bind(this)
this.setGender = this.setGender.bind(this)
}
setName(name) {
this.name = name
}
setAge(age) {
this.age = age
},
setGender(gender) {
this.gender = gender
}
}
```
## Easy Way
Bind all methods in constructor.
```js
import es6ClassBindAll from 'es6-class-bind-all'
class Person {
constructor() {
this.name = 'Jack'
this.age = 20
this.gender = 'male'
es6ClassBindAll(this)
}
setName(name) {
this.name = name
}
setAge(age) {
this.age = age
},
setGender(gender) {
this.gender = gender
}
}
```
Or you can bind specified methods in constructor depend on your situation.
```js
es6ClassBindAll(this, ['setGender'])
```
## Install
```bash
yarn add es6-class-bind-all --dev
```
or npm
```bash
npm install es6-class-bind-all --save-dev
```
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.