ESLint: Enforce that class methods utilize this (class-methods-use-this)

Inside a Stimulus controller, I have a method like this to prevent submitting the form when the Return key is pressed:

keypress(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
  }
}

The javascript linter is complaining

Enforce that class methods utilize this (class-methods-use-this)

If a class method does not use this , it can sometimes be made into a static function. If you do convert the method into a static function, instances of the class that call that particular method have to be converted to a static call as well ( MyClass.callStaticMethod() )
…
This rule is aimed to flag class methods that do not use this .

It’s easy enough to disable the linter for this particular method. But I am wondering if there’s a better way that I’m missing.

1 Like

It’s easy enough to disable the linter for this particular method.

I’d go the other direction and delete that rule from your .eslintrc :grimacing:

But I am wondering if there’s a better way that I’m missing.

This would appease your linter, but is undeniably worse:

export default class extends Controller {
  static keypress(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
    }
  }

  keypress(event) {
    this.constructor.keypress(event);
  }
}

:golfing_man: Another not-recommended not-better way:

export default class extends Controller {
  get keypress() {
    return keypress;
  }
}

function keypress(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
  }
}

I would do that but my client is passionately in love with his lint config.

LOL, thanks for these ideas. I’m glad to know I’m not out in left field.

Also, consider renaming your keypress() method to describe the outcome instead of just repeating the event name.

Avoid action names that simply repeat the event’s name, such as click , onClick , or handleClick:

<button data-action="click->profile#click">Don't</button>

Instead, name your action methods based on what will happen when they’re called:

<button data-action="click->profile#showDialog">Do</button>

This will help you reason about the behavior of a block of HTML without having to look at the controller source.

↝ https://stimulusjs.org/reference/actions#naming-conventions

1 Like