Javascript - Creating a closure with an event handler

23 November 2020, 3:15 am by antelove19


Sources:

Oreilly Head First JavaScript Programming 1


Creating a closure with an event handler

Let’s look at one more way to create a closure. We’ll create a closure with an event handler, which is something you’ll see fairly often in JavaScript code. We’ll start by creating a simple web page with a button and a

element to hold a message. We’ll keep track of how many times you click the button and display the tally in the
.

Here’s the HTML and a tiny bit of CSS to create the page. Go ahead and add the HTML and CSS below into a file named “divClosure.html”.

<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>Click me!</title>
        <style>
            body, button { margin: 10px; }
            div { padding: 10px; }
        </style>
        <script>
            // JavaScript code here
        </script>
    </head>

    <body>
        <button id="clickme">Click me!</button>
        <div id="message"></div>
    </body>

</html>

Next, let’s write the code. Now, you could write the code for this example without using a closure at all, but as you’ll see, by using a closure, our code is more concise, and even a bit more efficient.

Click me! without a closure

Let’s first take a look at how you’d implement this example without a closure.

var count = 0;

window.onload = function() {
    var button = document.getElementById("clickme");

    button.onclick = handleClick;
};

function handleClick() {
    var message = "You clicked me ";
    var div = document.getElementById("message");

    count++;

    div.innerHTML = message + count + " times!";
}

Click me! with a closure

The version without a closure looks perfectly reasonable, except for that global variable which could potentially cause trouble. Let’s rewrite the code using a closure and see how it compares. We’ll show the code here, and take a closer look after we test it.

window.onload = function() {
    var count = 0;
    var message = "You clicked me ";
    var div = document.getElementById("message");
    var button = document.getElementById("clickme");

    button.onclick = function() {
        count++;
        div.innerHTML = message + count + " times!";
    };
};

  1. Oreilly, "Oreilly Head First JavaScript Programming", page 503 




Video not yet
0 comment