StimulusJS How to set an instance variable on connect

Viewed 2173

I am trying to get into stimulusJS

import { Controller } from 'stimulus'

export default class extends Controller {

  static targets = [
    'foo',
  ]

  connect() {
    const fooValue = this.fooTarget.value
    console.log(this.fooValue) // 7
    this.someFunction()
  }

  someFunction(){
    console.log(this.fooValue) // undefined
  }

}

I want to be able to get this value on connect as I want to know if it has changed.

1 Answers

Your code declares const variable within the scope of connect() function. But you should use this (Stimulus Controller) property instead:

...
  connect() {
    this.fooValue = this.fooTarget.value
...
Related