0

So I'm trying to keep my javascript project organised by using classes and an init function, now I'm having this weird problem I never have experienced before. This is my code:

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

    document.getElementById("authenticationVerify").onclick = app.authenticate;
    document.getElementById("btnSendSMS").onclick = app.submitForm;
}

window.onload = init;

And HTML (simplified)

<body>
    <main>
        <form id="formSendSMS">
            <input type="button" name="send" id="btnSendSMS" value="Versturen">
        </form>

        <div id="authentication-prompt">
            <form>
                <input type="button" name="login" id="authenticationVerify" value="Log in" class="button blue">
            </form>
        </div>
    </main>
    <script src="js/mainBack.js" type="text/javascript"></script>
</body>

</html>

As you can see in the console, I get "undefined" when I activate the second button press, but I really don't know why this is happening, since the 'app' is not getting redeclared.

'undefined' in console

Kind regards, Jasper

Jasper B
  • 346
  • 3
  • 17

1 Answers1

1

That is not a proper way to catch click event. From your js code, I have succeeded to make a working example.

Also, JS functions cant be called without parentheses. A great example is given here.

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

 
    document.getElementById("authenticationVerify").onclick = function(e){app.authenticate()};
    document.getElementById("btnSendSMS").onclick = function(e){app.submitForm()};
}


window.onload = init;
<button id="authenticationVerify">AUTH</button>
<button id="btnSendSMS">SMS</button>
kalle
  • 144
  • 1
  • 9
  • 1
    Yea I just figured it out that I shouldn't directly call the app function from the onclick function from the button. Thanks for the help. And PS: I used method refrence to link the method that's why there aren't any parentheses – Jasper B Jul 26 '21 at 14:02