andreypopp / autobind-decorator

Decorator to automatically bind methods to class instances

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Usage outside classes

kasperlewau opened this issue · comments

Sometimes I'll find myself wiring up a singleton for use throughout my application. Said singleton is really just an object with a set of exposed methods.

Some of these methods modify the exposed singleton through Object.assign. Now, I don't want to pollute my codebase with references to this, as such autobind comes to mind as I use it throughout my classes.

export default function Lab () {
  function meth () {
    const recipe = { 'acetone', 'lithium', 'sulfuric acid' };
    Object.assign(this, { recipe });
  }

  Object.assign(this, { meth });
}

Now, the exposed method can be prebound with .bind just fine;

export default function Lab () {
  Object.assign(this, {
    meth: meth.bind(this)
  });
}

But if I wan't to call it before exposure (insert w/e reason);

export default function Lab () {
  function meth () { /**/ }

  meth.call(this);

  Object.assign(this, {
    meth: meth.bind(this)
  });
}

I'd much rather have:

import autobind from 'autobind-decorator';

export default function Lab () {
  @autobind
  function meth () { /**/ }

  Object.assign(this, { meth });
}

I have no clue as to how hard this would be to implement, nor if it would ever work. Thoughts?

Decorators don't modify the original function or class. Please checkout the spec. You could use autobind as a higher order function/class in your case.