Event handling (overview) | 您所在的位置:网站首页 › eventlisteners › Event handling (overview) |
The most flexible way to set an event handler on an element is to use the EventTarget.addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget.removeEventListener). Note: The ability to add and remove event handlers allows you to, for example, have the same button performing different actions in different circumstances. In addition, in more complex programs cleaning up old/unused event handlers can improve efficiency. Below we show how a simple greet() function can be set as a listener/event handler for the click event (you could use a lambda function instead of a named function if desired). Note again that the event is passed as the first argument to the event handler. jsconst btn = document.querySelector("button"); function greet(event) { console.log("greet:", event); } btn.addEventListener("click", greet);The method can also take additional arguments/options to control aspects of how the events are captured and removed. More information can be found on the EventTarget.addEventListener reference page. Using an Abort SignalA notable event listener feature is the ability to use an abort signal to clean up multiple event handlers at the same time. This is done by passing the same AbortSignal to the addEventListener() call for all the event handlers that you want to be able to remove together. You can then call abort() on the controller owning the AbortSignal, and it will remove all event handlers that were added with that signal. For example, to add an event handler that we can remove with an AbortSignal: jsconst controller = new AbortController(); btn.addEventListener( "click", (event) => { console.log("greet:", event); }, { signal: controller.signal }, ); // pass an AbortSignal to this handlerThen the event handler created by the code above can be removed like this: jscontroller.abort(); // removes any/all event handlers associated with this controller |
CopyRight 2018-2019 实验室设备网 版权所有 |