Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a const string in my Stimulus JS controller?

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

like image 383
daveomcd Avatar asked Jan 25 '23 22:01

daveomcd


2 Answers

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 );
    // ...
  }

}
like image 53
Dai Avatar answered Feb 14 '23 11:02

Dai


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 );
    // ...
  }
}
like image 33
Adrien Avatar answered Feb 14 '23 09:02

Adrien