gitmyhub

autobind-decorator

JavaScript ★ 7 updated 11y ago ⑂ fork

Decorator to automatically bind methods to class instances

A JavaScript decorator that automatically binds class methods to their instance, fixing the common 'this is undefined' bug.

JavaScriptBabelcore-jssetup: moderatecomplexity 2/5

Explanation

This is a small JavaScript utility that solves a common JavaScript gotcha: when you pass a method from a class to another function, this stops pointing to the object it came from. Normally you'd have to manually "bind" the method to fix this. This decorator automates that fix, so you don't have to think about it.

Here's the practical problem it solves. Imagine you have a React component with a method that updates some data. If you pass that method to a button's onClick handler, the method loses track of which component it belongs to—so this becomes undefined or points to the wrong thing. With this decorator, you just add @autobind above the method, and it automatically remembers which component it belongs to, no matter where you use it.

You can use the decorator two ways: put it on individual methods you want to protect, or put it on the entire class to automatically bind all methods at once. Either way, the result is cleaner code—you write methods the straightforward way and let the decorator handle the binding mechanics behind the scenes.

The decorator syntax (the @ symbol) isn't standard JavaScript yet, so you need Babel or another transpiler to convert your code into something browsers can actually run. This was more relevant when the code was written; modern JavaScript has other ways to handle this problem (like arrow functions), but the decorator approach is still valid and some developers prefer it for its clarity. The README notes you should also install core-js to handle some JavaScript features the decorator depends on.

Where it fits