autobindr
Look ma, no
bind
!
The fast, easy and convenient way to automatically bind "class" methods to the instance.
Go from this
<button onClick=thisonButtonClick>click</button>
to this
<button onClick=thisonButtonClick>click</button>
With simple
;
autobind
should be called from within the class constructor function, passing this
as an argument.
While this package was developed with React in mind, it works the same way with vanilla JS classes or any other JS framework utilizing classes.
It will skip all React lifecycle methods
Installation
npm install --save autobindr
This assumes that you’re using npm package manager with a module bundler like Webpack, Rollup or Browserify to consume CommonJS modules.
If you don’t yet use npm or a modern module bundler, and would rather prefer a single-file UMD build that makes autobind
function available as a global. You can grab the latest version from unpkg CDN here, or production-ready minified version(<1kb) - here and drop script
tag right into your HTML, although I don't recommend you to do so.
Importing
ES6 modules
;
CommonJS
var autobind = ;
UMD
var autobind = windowautobind;
API
autobind(context, [options])
Automatically binds "class" methods to provided context(usually lexical this
). To be called in constructor
.
{ super; ;}
options: {only: Array<string>, skip: Array<string>, pattern: RegExp}
only: Array<string>
- Array of method names, if provided, only this methods will be bound to the context
// bind only "onButtonClick" and "onFormSubmit" methods
skip: Array<string>
- Array of method names, if provided, this methods will be skipped(not bound to the context)
// do not bind "onFormSubmit" method
pattern: RegExp
- if provided, regex will be executed on each method name
// bind all methods starting with "handle" (handleClick, handleFormSubmit, handleDelete, etc.)
Example
; Component { super; thisstate = counter: 0 ; ; } { this; } { return <div class="counter"> thisstatecounter <button onClick=thisonButtonClick>Inc</button> </div> ; } ReactDOM;