This is the 23rd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Writing in the front

The essence of an event is a way of communication between the components of a program, as well as an implementation of asynchronous programming. DOM supports a large number of events. How do I get DOM nodes to listen for events?

An overview of the

The DOM node’s event operations (listening and firing) are defined in the EventTarget interface. This interface is deployed on all node objects, as well as other built-in browser objects that require event communication (e.g., XMLHttpRequest, AudioNode, AudioContext).

This interface mainly provides three instance methods.

  • addEventListener(): a listener function for binding events
  • removeEventListener(): Removes listeners for events
  • dispatchEvent(): Trigger event

EventTarget.addEventListener()

EventTarget. AddEventListener () used in the current node, or objects (i.e., deployed EventTarget interface object), the monitoring function defines a specific event. Once this event occurs, the listener function is executed. This method does not return a value.

target.addEventListener(type, listener[, useCapture]);
Copy the code

The method takes three arguments.

  • type: Event name, case sensitive.
  • listener: Listener function. This listener function is called when an event occurs.
  • useCapture: Boolean value if set totrue, indicating that the listener will fire during the capture phase (see Propagation of Events later). This parameter is optional. The default value isfalse(Listeners are only fired during the bubble phase).

Here’s an example.

function hello() {
  console.log('Hello world');
}

var button = document.getElementById('btn');
button.addEventListener('click', hello, false);
Copy the code

In the code above, the Button node’s addEventListener() method binds hello(), a listener for the click event, which is only fired during the bubble phase.

There are two things to note about parameters.

First, the second argument, in addition to the listener function, can be an object with a handleEvent method that has the same effect as the listener function.

buttonElement.addEventListener('click', { handleEvent: function (event) { console.log('click'); }});Copy the code

In the code above, the second argument to the addEventListener() method is an object with a handleEvent() method.

Second, the third parameter, in addition to the Boolean value useCapture, can also be a listener configuration object that customizes event listening behavior. This object has the following properties.

  • capture: Boolean value if set totrueIs triggered during the capture phase. The default isfalse, triggered during the bubbling phase.
  • once: Boolean value if set totrue, indicating that the listener function is automatically removed after being executed once and will no longer listen for the event. The default value for this property isfalse.
  • passive: Boolean value, set totrueIs used to disable listening function callspreventDefault()Methods. If it does, the browser ignores the request and prints a warning to the console. The default value for this property isfalse.
  • signal: This property takes the value of an AbortSignal object, which sets up a signal channel for the listener to signal when needed to remove the listener.

The following is an example of the once property, which allows the listener function to be executed only once.

Element.addeventlistener ('click', function (event) {// code executed only once}, {once: true});Copy the code

The addEventListener() method can add multiple different listener functions for the same event on the current object. These functions fire in order of addition, that is, they are added first. If you add the same listener for the same event more than once, the function is executed only once, and any additional additions are automatically removed (you don’t need to manually remove them using the removeEventListener() method).

function hello() {
  console.log('Hello world');
}

document.addEventListener('click', hello, false);
document.addEventListener('click', hello, false);
Copy the code

Executing the code above, clicking on document will only output a Hello World line.

If you want to pass parameters to a listener function, you can wrap the listener function with an anonymous function.

function print(x) {
  console.log(x);
}

var el = document.getElementById('div1');
el.addEventListener('click', function () { print('Hello'); }, false);
Copy the code

The code above passes an argument to the listener function print via an anonymous function.

Listen for this inside the function, which points to the object of the current event.

<p id="para">Hello</p> var para = document.getelementbyid ('para'); para.addEventListener('click', function (e) { console.log(this.nodeName); // "P" }, false);Copy the code

In the code above, the this inside the listener refers to para, the object of the event.

EventTarget.removeEventListener()

EventTarget. RemoveEventListener () method is used to remove the addEventListener () method to add events to monitor function. This method does not return a value.

div.addEventListener('click', listener, false);
div.removeEventListener('click', listener, false);
Copy the code

The parameters of the removeEventListener() method are identical to those of the addEventListener() method. Its first argument, event type, is case sensitive.

Note that the listener removed by the removeEventListener() method must be the same listener added by the addEventListener() method and must be on the same element node.

div.addEventListener('click', function (e) {}, false);
div.removeEventListener('click', function (e) {}, false);
Copy the code

In the code above, the removeEventListener() method is invalid because the listener function is not the same anonymous function.

element.addEventListener('mousedown', handleMouseDown, true);
element.removeEventListener("mousedown", handleMouseDown, false);
Copy the code

In the code above, the removeEventListener() method is also invalid because the third parameter is different.

EventTarget.dispatchEvent()

EventTarget. DispatchEvent () method on the current node trigger specified event, triggering the implementation of monitoring function. This method returns a Boolean, false as long as one of the listener functions calls event.preventDefault (), true otherwise.

target.dispatchEvent(event)
Copy the code

The parameter to the dispatchEvent() method is an instance of an Event object (see the Event Objects section).

para.addEventListener('click', hello, false);
var event = new Event('click');
para.dispatchEvent(event);
Copy the code

The above code fires the click event on the current node.

An error is reported if the parameter to the dispatchEvent() method is empty or not a valid event object.

The following code determines whether the event was canceled based on the return value of the dispatchEvent() method.

var canceled = ! cb.dispatchEvent(event); If (canceled) {console.log(' event canceled '); } else {console.log(' event not cancelled '); }Copy the code