Stimulus Discourse

Private variables within a controller

Hi friends

Please see below - i’m wanting to create a variable from within a particular instance of a stimulus class. Perhaps if you see the below code, you might spot some obvious problems when using javascript.

Was seeking a quick pointer. Chrs

import { Controller } from "stimulus";

export default class extends Controller {
  let abortController = new AbortController();
  let signal = abortController.signal;

  connect(){    
    console.log(this.abortController) // not working as expected.
    console.log(this.signal) // not working as expected.
  }

 hide(){
   console.log(this.abortController) // not working as expected.
 }
  }

remove the let

import { Controller } from "stimulus";

export default class extends Controller {
  abortController = new AbortController();
  signal = abortController.signal;

  connect(){    
    console.log(this.abortController) // not working as expected.
    console.log(this.signal) // not working as expected.
  }

 hide(){
   console.log(this.abortController) // not working as expected.
 }
 }

or maybe better to initilialize them in the connect

import { Controller } from "stimulus";

export default class extends Controller {
  
  connect(){    
    this.abortController = new AbortController();
    this.signal = abortController.signal;
  }

 hide(){
   console.log(this.abortController) // not working as expected.
 }
 }
1 Like

@adrienpoly thanks for the tip; and also your work on stimulus