UNPKG

1.02 kBTypeScriptView Raw
1declare namespace autoBind {
2 interface Options {
3 /**
4 Bind only the given methods.
5 */
6 readonly include?: ReadonlyArray<string | RegExp>;
7
8 /**
9 Bind methods except for the given methods.
10 */
11 readonly exclude?: ReadonlyArray<string | RegExp>;
12 }
13}
14
15/**
16Automatically bind methods to their class instance.
17
18@param self - Object with methods to bind.
19
20@example
21```
22import autoBind = require('auto-bind');
23
24class Unicorn {
25 constructor(name) {
26 this.name = name;
27 autoBind(this);
28 }
29
30 message() {
31 return `${this.name} is awesome!`;
32 }
33}
34
35const unicorn = new Unicorn('Rainbow');
36
37// Grab the method off the class instance
38const message = unicorn.message;
39
40// Still bound to the class instance
41message();
42//=> 'Rainbow is awesome!'
43
44// Without `autoBind(this)`, the above would have resulted in
45message();
46//=> Error: Cannot read property 'name' of undefined
47```
48*/
49declare function autoBind<SelfType extends {[key: string]: any}>(
50 self: SelfType,
51 options?: autoBind.Options
52): SelfType;
53
54export = autoBind;