Peki
Peki

Reputation: 25

My Javascript code doesn't work anymore after I wrap it in a self-calling function

I see in a lot of code that people wrap everything in a self-calling function so everything stays more or less private. Doing this to my code resulted in it not working anymore.

I Googled a bit about it and saw that it is good practice to place the whole source file in a self-calling function so I decided to try it too. I tried this with my little piece of code and it just doesn't work anymore after doing it.

(function($) {
    const auth = firebase.auth();

    function logIn(){
        window.alert("pressed log in button");
        var userEmail = document.getElementById("txtEmail").value;
        var userPass = document.getElementById("txtPassword").value;

        auth.signInWithEmailAndPassword(userEmail,userPass).catch(function(error) {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
            window.alert("Error : " + errorMessage);
        });
    };
});

I expected the code to work but whenever I press the button that calls the logIn function I get the following error message: "Uncaught ReferenceError: logIn is not defined at HTMLButtonElement.onclick". This clearly shows that turning my code into a self-calling function makes it not work anymore.

Upvotes: 0

Views: 169

Answers (1)

Quentin
Quentin

Reputation: 943560

after I wrap it in a self-calling function

You haven't wrapped it in an IIFE. You've wrapped it in a function which is never called. To make it an IIFE you need to call it (e.g. with (whatever_you_want_assigned_to_the_$_argument) at the end).

I Googled a bit about it and saw that it is good practice to place the whole source file in a self-calling function

This is because globals are bad. (That's a generalisation).

Uncaught ReferenceError: logIn is not defined at HTMLButtonElement.onclick

Since you don't assign any event handlers in your code, presumably your HTML looks like:

onclick="logIn()"

You are trying to call logIn, as a global.

Now, since the whole point of using an IIFE is to stop using globals, that doesn't work.

Bind your event handlers with addEventListener, or (since you seem to be using jQuery) the jQuery wrapper around that instead.

(function($) {
    function logIn(){
        window.alert("pressed log in button");
    }
    $("button#logIn").on("click", logIn);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id=logIn>Log In</button>

Upvotes: 4

Related Questions