The internal options for addEventListener and a better approach in handling events
8/30 Solution and Explanation for LeetCode’s JS challenge
So in past few solutions/articles I had defined what are polyfills and how and why they are created today’s problem is in similar domain where we are asked to create a polyfill for once event handler i.e. the function can only be called once
In order to understand this solution/polyfill implementation you should understand what are closures first and if you know cool! if not you can refer the previous solutions/articles in this series
once you have covered pre-requesites let’s jump into this solution
first let’s understand what are Event Listener In JavaScript
Lets break that even more into Events and Listeners
What Are Events?
Events are things that happen in the system you are programming — the system produces (or “fires”) a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window. There are many different types of events that can occur.
For example:
- The user selects, clicks, or hovers the cursor over a certain element.
- The user chooses a key on the keyboard.
- The user resizes or closes the browser window.
- A web page finishes loading.
- A form is submitted.
- A video is played, paused, or ends.
- An error occurs.
Now Coming to Next term
What are Event Listeners?
Event listeners as the the name suggests listen to all the at events which can occur in system/application like we discussed above besides that we can also attach an event listener to any element in our application by using addEventListener function.
so after adding a listener we also need to take some action or call a function on it’s call for that purpose we can use a Event Handler
Now a naturally occuring question is what are event handlers?
So if you remeber we discussed about callbacks and how we can use function as first class objects to pass inside of other function as arguments in a similar way eventListner can take a callback function which is eventHandler which can perform some operations.
So now when we have understood what are events, event listeners and event handlers lets dive deeper into addEventListener method
The addEventListener() method is the recommended way to register an event listener. The benefits are as follows:
- It allows adding more than one handler for an event. This is particularly useful for libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries or extensions.
- In contrast to using an onXYZ property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
- It works on any event target, not just HTML or SVG elements.
addEventListener method takes few arguments major ones are
- type
A case-sensitive string representing the event type to listen for. - listener
The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be null, an object with a handleEvent() method, or a JavaScript function. See The event listener callback for details on the callback itself. - options Optional
An object that specifies characteristics about the event listener. The available options are:
- capture Optional
A boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. If not specified, defaults to false. - once Optional
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false. - passive Optional
A boolean value that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. If not specified, defaults to false — except that in browsers other than Safari, defaults to true for the wheel, mousewheel, touchstart and touchmove events. See Improving scrolling performance with passive listeners to learn more. - signal Optional
An AbortSignal. The listener will be removed when the given AbortSignal object’s abort() method is called. If not specified, no AbortSignal is associated with the listener.
So you see here in options we have once which helps you get more control over handling the event internally JavaScript must be using some function like we are have defined in our solution to handle that.
Code
/**
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
let called = false
return function(...args){
if (called) return undefined;
called = true
return fn(...args)
}
};
/**
* let fn = (a,b,c) => (a + b + c)
* let onceFn = once(fn)
*
* onceFn(1,2,3); // 6
* onceFn(2,3,6); // returns undefined without calling fn
*/
Conclusion
Knowing how events are propagated and how you can listen to them will help you create more robust application and understanding the internals on how they are actually handled will give you insight on how to use them efficiently will make your application fast and reliable.
Previous Article — https://varnitsharma-102.medium.com/what-is-polyfilling-in-javascript-and-how-does-callbacks-works-246719161e4a
Problem — https://leetcode.com/problems/allow-one-function-call/description/