0

Recently I've started practicing with javascript/jQuery. I have a class Questionnaire.

class Questionnaire {
    constructor (json, container) {
        // constructor stuff
    }

    processAnswers() {
        // Do something
    }   

    showQuestionnaire() {
        // A lot of stuff happens here
        // HTML gets build in this method and added to an excisting container. 
        // The element with class 'button_confirm' gets generated here as well.
        // this.container is an excisting HTML DOM-Object (Div)

        $(this.container).find('.button_confirm').on('click', function () {
            this.processAnswers();  
        });
    }   
}

All goes well, but when I press the button and trigger the event, I get an error telling me that processAnswers is not a function.

What am I doing wrong? Why can't I call processAnswers from here? It's probably an easy fix, but I don't see the mistake.

Thanks in advance.

Giltix
  • 3
  • 3

1 Answers1

1

You need to use arrow function here, that is because this will point to window object inside the click event handler, but you require the current context

$(this.container).find('.button_confirm').on('click', (e)=> {
            this.processAnswers();  
        });
brk
  • 48,835
  • 10
  • 56
  • 78
  • Or declare a `constant` before the function pointing to `this.processAnswers()`. An arrow function is much cleaner. – Mouser Nov 02 '19 at 13:31