Cannot call my Event.RemoveCallback from another method within my class

Hello,

I have a method within a class which uses an event listener to periodically update an image, and another method to stop the updating. here is the rough outline:

class Imagery {
    shouldUpdate: boolean;
    removeListener: Event.RemoveCallback;    

    generateImage() {
        this.removeListener = viewer.scene.postRender
            .addEventListener(function () {
                if (this.shouldUpdate) {
                    thisMaterial.uniforms.texture = thisRefreshImage();
                    this.shouldUpdate= false;
                }
            })
   }
   
   stopRefreshingImage() {
       this.removeListener();   
   }
}

So I get the Event.RemoveCallback when adding the event listener, and store it in a global variable removeListener. I then invoke the callback in stopRefreshImage(). However, when I invoke the callback, the event listener in generateImage() does not stop. It does stop if I invoke this.removeListener from within generateImage() though.

I understand this is a scoping / lexical issue that comes down to dealing with the keyword this. However, when I look online for how to handle the situation, they usually suggest changing the callback function to either be an arrowkey function, or to .bind(this) at the end of the callback function declaration. As far as I can tell, I do not have the luxury of being able to modify the callback function being returned by addEventListener, so these solutions are not feasible.

Any ideas on how I can get around this problem? Thanks for any advice you may have :slight_smile:

Hello there,

One issue may be that from within a new function block, this is undefined.

You can get around this by assigning a temporary variable before the function:

const that = this;
function () {
   if (that.shouldUpdate) {
      ...
   }
}

Or you can use an arrow function, which retains the same scope, including this.


.addEventListener(() => {
   if (this.shouldUpdate) {
    ...
  }
})