// and it would run each time the button is clicked
alert('Button was clicked')
}
})
</script>
</body>
</html>
...
...
@@ -36,8 +36,8 @@ Each time the button is clicked, it displays a message saying that the button wa
Let's tease apart the code responsible for making button clicks display the message.
First, note that `() => alert('Button was clicked')` is a *function* in JS.
When this function is called, it causes the message `Button was clicked` to appear.
Then `button.onclick = ...` tells the browser "this is the function I want to attach to the click action on `button`.
When a user interacts with the webpage, the browser figures out whether the button was clicked, and if so, it runs the function stored in `button.onclick`.
Then `button.addEventListener('click', ...)` tells the browser "I want the click action on `button` to call this function".
When a user interacts with the webpage, the browser figures out whether the button was clicked, and if so, it runs the "click handler" function.
## How doesn't this work?
...
...
@@ -65,7 +65,7 @@ So why doesn't JS use an interface like one of these?
2. This approach solves the issue of not being able to respond to multiple events: we could just add an `if (button2.wasClicked())` inside the loop.
However, it has a more subtle problem.
The loop may run billions of times before the user actually clicks the button.
Since our program can't actually do anything until the user finally clicks the button, this is an incredible waste of the processor's time.
Since our program won't actually do anything until the user finally clicks the button, this is a huge waste of the processor's time.
We see that the "event handler" approach used by JS has two main benefits: it can easily set up handlers for thousands of events at once, and no JS code runs while we wait for an event to occur.
...
...
@@ -79,14 +79,16 @@ In [this example](lock1.html), we make a combination lock with 4 digits and want
In Node.js, an asynchronous task that produces chunks of data is represented as a "readable stream".
To process a readable stream, we need to specify the callback function that will be used to process each chunk of data.
We can also register a callback to run when the stream finishes emitting data.
In Node.js, the `.on()` method for "event emitters" works similarly to the `.addEventListener()` method for DOM elements in the browser.
As we saw above, reading a file is a prime example of a stream.
Indeed, the `fs` module provides a function [`fs.createReadStream()`](https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options) to make a readable stream for a given file.