Stimulus Discourse

Passing a callback function


We have an integration with a third party that uses a callback function that passed into one of their methods. The problem is that the callback loses its context and can no longer access this.

Within the controller:

  makeRequest() {
    let response =, this.callback)

  callback(response) {
    if(response.success) {
      this.success(response)  // Won't work because "this" is now within the third party api

  success(response) {
    // do lots of things within the controller

Before Stimulus, the callback called nameSpace.callback(), but I don’t know how to access the controller namespace. For example, in the contrived example above, I need to be able to pass the results into the the success controller method.

Should this be done by triggering an event?


You need to bind the function reference to the controller or use an inline function (I’m assuming params is a property, otherwise you’ll have to bind that too):

Bound function

let response =, this.callback.bind(this))

Inline function

let response =, event => this.callback(event))


Thanks Kasper! That is exactly what I needed!