Stimulus Discourse

Passing a callback function


#1

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 = thirdParty.api.call(this.params, this.callback)
  }

  callback(response) {
    console.log(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?


#2

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 = thirdParty.api.call(this.params, this.callback.bind(this))

Inline function

let response = thirdParty.api.call(this.params, event => this.callback(event))

#3

Thanks Kasper! That is exactly what I needed!