react-auto-bind
Automatically bind methods to their class instance. This is optimized for react. It doesn't bind render and other lifecycle methods.
Install
$ npm install --save react-auto-bind
Usage
const autoBind = ; { thisname = name; ; } { return ` is awesome!`; } const unicorn = 'Rainbow'; // Grab the method off the class instanceconst message = unicornmessage; // Still bound to the class instance;//=> 'Rainbow is awesome!' // While message() would not be bound & would have resulted in;//=> Error: Cannot read property 'name' of undefined
Bind only some methods
const autoBind = ; { thisname = name; ; } { return ` is amazing!`; } { return ` is undefined!`; } const buckbeak = 'Buckbeak'; // Grab the method off the class instanceconst message = buckbeakmessage;const amaze = buckbeakamaze; // Still bound to the class instance;//=> 'Buckbeak is amazing!' // Without `autoBind(this)`, the above would have resulted in;//=> Error: Cannot read property 'name' of undefined
API
autoBind(self, [...bindOnly])
Bind methods in self
to their class instance. Returns the self
object.
self
Type: Object
Object with methods to bind.
bindOnly
Type: Strings
If more than one parameters are passed then only those methods are bound.
Related
- bind-methods - Bind all methods in an object to itself or a specified context
- auto-bind - Automatically bind all methods to their class instance.