EventTarget interface

The essence of the event is a communication method between the various components of the program, and it is also an implementation of asynchronous programming. DOM supports a large number of events. This chapter begins to introduce DOM event programming.

Overview

DOM event operations (monitoring and triggering) are all defined in the EventTarget interface. All node objects deploy this interface, and other built-in browser objects that require event communication (for example, XMLHttpRequest, AudioNode, and AudioContext) also deploy this interface.

The interface mainly provides three instance methods.

-addEventListener: listener function for binding events -removeEventListener: the listener function to remove the event -dispatchEvent: trigger event

EventTarget.addEventListener()

EventTarget.addEventListener() is used to define a listener function for a specific event on the current node or object. Once this event occurs, the monitoring function will be executed. This method has no return value.

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

The method accepts three parameters.

-type: Event name, case sensitive. -listener: listener function. When an event occurs, the listener function will be called. -useCapture: Boolean value, indicating whether the listener function is triggered in the capture phase (refer to the "Propagation of Events" section below), the default is false (the listener function is only triggered in the bubbling phase). This parameter is optional.

Below is an example.

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

var button = document.getElementById("btn");
button.addEventListener("click", hello, false);

In the above code, the addEventListener method of the button node is bound to the listener function hello of the click event, which is only triggered in the bubbling phase.

Regarding the parameters, there are two places to pay attention to.

First of all, in addition to the listener function, the second parameter can also be an object with the handleEvent method.

buttonElement.addEventListener("click", {
  handleEvent: function (event) {
    console.log("click");
  },
});

In the above code, the second parameter of the addEventListener method is an object with a handleEvent method.

Secondly, in addition to the boolean value useCapture, the third parameter can also be a property configuration object. The object has the following properties.

-capture: Boolean value, indicating whether the event triggers the listener function in the capture phase. -once: Boolean value, indicating whether the monitoring function is triggered only once and then automatically removed. -passive: Boolean value, which means that the listener function will not call the preventDefault method of the event. If the monitoring function is called, the browser will ignore this request and output a line of warning on the monitoring station.

If you want the event listener function to be executed only once, you can turn on the once property of the property configuration object.

element.addEventListener(
  "click",
  function (event) {
    // code that is executed only once
  },
  { once: true }
);

The addEventListener method can add multiple different listener functions for the same event of the current object. These functions are triggered in the order of addition, that is, they are added first and triggered first. If you add the same listener function for the same event multiple times, the function will only be executed once, and the extra additions will be automatically removed (you don't need to use the removeEventListener method to manually remove).

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

document.addEventListener("click", hello, false);
document.addEventListener("click", hello, false);

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

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

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

var el = document.getElementById("div1");
el.addEventListener(
  "click",
  function () {
    print("Hello");
  },
  false
);

The above code passes an argument to the monitor function print through an anonymous function.

The this inside the listener function points to the object where the current event is located.

// HTML code is as follows
// <p id="para">Hello</p>
var para = document.getElementById("para");
para.addEventListener(
  "click",
  function (e) {
    console.log(this.nodeName); // "P"
  },
  false
);

In the above code, the this inside the listener function points to the object para where the event is located.

EventTarget.removeEventListener()

The EventTarget.removeEventListener method is used to remove the event listener function added by the addEventListener method. This method has no return value.

div.addEventListener("click", listener, false);
div.removeEventListener("click", listener, false);

The parameters of the removeEventListener method are exactly the same as the addEventListener method. Its first parameter "event type" is case sensitive.

Note that the listener function removed by the removeEventListener method must be the listener function added by the addEventListener method, and must be in the same element node, otherwise it will be invalid.

div.addEventListener("click", function (e) {}, false);
div.removeEventListener("click", function (e) {}, false);

In the above code, 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);

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

EventTarget.dispatchEvent()

The EventTarget.dispatchEvent method triggers the specified event on the current node, thereby triggering the execution of the listener function. This method returns a boolean value. As long as a listener function calls Event.preventDefault(), the return value is false, otherwise it is true.

target.dispatchEvent(event);

The parameter of the dispatchEvent method is an instance of the Event object (see the "Event Object" chapter for details).

para.addEventListener("click", hello, false);
var event = new Event("click");
para.dispatchEvent(event);

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

If the parameter of the dispatchEvent method is empty or is not a valid event object, an error will be reported.

The following code determines whether the event has been cancelled based on the return value of the dispatchEvent method.

var canceled = !cb.dispatchEvent(event);
if (canceled) {
  console.log("Event canceled");
} else {
  console.log("The event was not cancelled");
}