8

I'm wanting to set a const variable for a CSS selector for my controller, instead of having it hard coded throughout my controller. I had put the declaration in the initialize() of my controller, but I'm getting an error that the variable wasn't declared. What's the correct way of doing this?

Current Attempt

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["form"]

  initialize() {
    const seasonInputSelector = "input[id$='_season']"
  }

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll(seasonInputSelector)
    // ...
  }

}

Error: ReferenceError: seasonInputSelector is not defined

daveomcd
  • 6,367
  • 14
  • 83
  • 137
  • You're declaring `seasonInputSelector ` as a **local** inside the `initialize` method. It doesn't exist outside of `initialize`. You need to move it to be a static class-level field (as your class is anonymous you can't do this) or a const in the module's scope. – Dai Jun 27 '20 at 19:36

2 Answers2

13

Use a const variable in the module's root scope:

import { Controller } from "stimulus"

const seasonInputSelector = "input[id$='_season']";

export default class extends Controller {
  static targets = ["form"]

  initialize() {
  }

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll( seasonInputSelector );
    // ...
  }

}
Dai
  • 141,631
  • 28
  • 261
  • 374
6

An alternative is to scope it inside your class

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["form"]
  seasonInputSelector = "input[id$='_season']";

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll( this.seasonInputSelector );
    // ...
  }
}
Adrien
  • 322
  • 4
  • 14
  • 2
    JavaScript/TypeScript don't allow for `static` fields in classes though, so this will add `seasonInputSelector` as a JavaScript prototype/instance property so it will be in **every instance** - in this case you're probably fine, but if you'll be creating many instances of this class then it should be declared as a class-level immediately after the `class` definition: see @zagoa's answer here: https://stackoverflow.com/a/48012789/159145 – Dai Jun 18 '21 at 14:25
  • 1
    Basically, on the line _after_ `class Controller`'s closing brace `}`, put `Controller.seasonInputSelector = "input[id$='_season']";` and change `this.seasonInputSelector` to `Controller.seasonInputSelector` – Dai Aug 19 '21 at 16:52