0

I have the following:

class Button_Event {
    add_click() {
        this.button_jquery_object.on('click', function(e){
            this.add_loading();

            run_function_by_name(this.ajax_callback).done(function() {
                this.remove_loading();
            });
        });
    }
}

But when I run it, the following error occurs:

Uncaught TypeError: this.add_loading is not a function

...and rightfully so. I'm trying to call a class' method inside an anonymous function. I feel as if I shouldn't do this but I need to do this. How can this be done?

I believe I'm looking to somehow enforce the "this" scope on my anonymous' functions body too.

coolpasta
  • 725
  • 5
  • 19

1 Answers1

0

Traditional solution: store this in a local variable

add_click() {
    const self = this;
    this.button_jquery_object.on('click', function(e){
        self.add_loading();
    });
}

Modern solution: use an arrow function, which automatically bind this from context

add_click() {
    this.button_jquery_object.on('click', (e) => {
        this.add_loading();
    });
}

Strange solution: manually bind this to the function

add_click() {
    this.button_jquery_object.on('click', function(e){
        this.add_loading();
    }.bind(this));
}
yyyy
  • 593
  • 2
  • 10