JavaScript 30 – Day 25: Self-unbinding Event Listeners

Welcome to my recap of Day 25 of the free JavaScript 30 online video course by Wes Bos. In case you really have not yet heard of the course, quickly head over to it and get started right away! 🙂

Please refer to the JavaScript 30 archive for all recap posts.

Objective…?

Day 9 is no challenge, but rather a lesson on event listeners in general, including bubbling, capturing, (stopping) propagation—and a pretty neat thing: self-unbinding.

Retrospection

Since I am really not new to JavaScript—I am working with it since almost twenty years now—the lession didn’t have much news for me.

Except, there was one thing I never heard of before. Not even … once.

What am I talking about? The once option for addEventListener(). 😀

Self-unbinding Event Listeners

When you want a callback run only a single time for a specific event, you usually had to remove or unattach the callback from the event manually, inside the callback itself.

Now, however, you can make use of a new option, once, passed to the addEventListener() function as part of an options object as third argument.

This could look like so:

someButton.addEventListener( 'click', handleUserRequest, {
    once: true
} );

As soon as the callback gets fired, it gets removed from the event. This means no matter how often you click on that button, there will be no further execution due to the click event being fired.

Before this video, I always was only passing a boolean true as third argument to addEventListener()—if necessary at all, since configuring an event listener for capturing is not what you do every day.

So, I had a look at addEventListener(), and look at that, the options object only landed a few versions back in the major browsers, with the once option even having been included very recently (e.g., in Firefox 50, with version 51.0.1 being the current stable). So yes, this is pretty new—not only to me. 🙂

But it is great!

And You?

JavaScript 30 is free! So, unless you already did this on your own, what’s your reason not to? 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *