You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+48-3
Original file line number
Diff line number
Diff line change
@@ -4,6 +4,8 @@ A class or method decorator which binds methods to the instance so `this` is alw
4
4
5
5
This is particularly useful for situations like React components, where you often pass methods as event handlers and would otherwise need to `.bind(this)`.
6
6
7
+
`autobind` is lazy and is only bound once. :thumbsup:
let method =component.method// .bind(component) isn't needed!
53
+
method() // returns 42
54
+
```
55
+
56
+
`@boundMethod` makes `method` into an auto-bound method, replacing the explicit bind call later.
57
+
58
+
### Legacy approaches:
59
+
33
60
```js
34
61
importautobindfrom'autobind-decorator'
35
62
@@ -48,23 +75,41 @@ let component = new Component(42)
48
75
let method =component.method// .bind(component) isn't needed!
49
76
method() // returns 42
50
77
51
-
52
78
// Also usable on the class to bind all methods
53
79
// Please see performance if you decide to autobind your class
54
80
@autobind
55
81
classComponent { }
56
82
```
57
83
84
+
```js
85
+
import {boundClass} from'autobind-decorator'
86
+
87
+
@boundClass
88
+
classComponent {
89
+
constructor(value) {
90
+
this.value= value
91
+
}
92
+
93
+
method() {
94
+
returnthis.value
95
+
}
96
+
}
97
+
98
+
let component =newComponent(42)
99
+
let method =component.method// .bind(component) isn't needed!
100
+
method() // returns 42
101
+
```
102
+
58
103
## Performance
59
104
60
-
`autobind` on a method is lazy and is only bound once. :thumbsup:
105
+
`autobind`(`boundMethod`) on a method is lazy and is only bound once. :thumbsup:
61
106
62
107
However,
63
108
64
109
> It is unnecessary to do that to every function. This is just as bad as autobinding (on a class). You only need to bind functions that you pass around. e.g. `onClick={this.doSomething}`. Or `fetch.then(this.handleDone)`
65
110
-- Dan Abramov
66
111
67
-
You should avoid using `autobind` on a class. :thumbsdown:
112
+
You should avoid using `autobind`(`boundClass`) on a class. :thumbsdown:
0 commit comments