JavaScript-events

The interaction between JavaScript and HTML is achieved through events. An event is a specific moment of interaction sent in a document or browser window. Use listeners (or handlers) to schedule events so that the corresponding code is executed when the event occurs. This model, called observer mode in traditional software engineering, supports loose coupling between the behavior of the page and the appearance of the page (HTML, CSS).

Event flow
While clicking the button, you also click the container element of the button, and even the entire page.
The event flow describes the order in which events are received from the page.
However, the event stream of IE is an event bubble, and the event stream of NetScape Communicator is an event capture stream.

Event bubbling

IE's event flow is called event bubbling, that is, the event is received by the most specific element (the node with the deepest nesting level in the document), and then propagates up to the less specific node.

<!DOCTYPE html>
<html>
<head>
	<title>Event</title>
</head>
<body>
	<div>Click Me</div>
</body>
</html>

Click the div element on the page. The click event will propagate in the following order:

  1. div
  2. body
  3. html
  4. The
    click event of the document object occurs on the div element. The click event propagates up the DOM tree and occurs on each level of the node until the document object.

All browsers support event bubbling. In IE5.5 and earlier versions, event bubbling skips the html element. In IE9, Firefox, Chrome, and Safari, the event is bubbled all the way to the window object.

Event capture

The idea of ​​event capture is that less specific nodes should receive the event earlier, and the most specific node should receive the event last.
The purpose of event capture is to capture an event before it reaches a predetermined target.
In the above example, in the case of event capture, click the div element in the following order to trigger the event

  1. document
  2. html
  3. body
  4. div
    event capture is the only event flow model supported by Netscape Communicator. IE9, Safari, Chrome, Opera, and FireFox all support it, but these browsers start capturing events from the window object. Version browsers do not support it, so use events whenever possible bubble

DOM event flow

"DOM2 level event" stipulates that the event flow includes three stages: event capture stage, at the target stage, and event bubbling.
The first thing that happens is the event capture, which provides an opportunity to intercept the event, and then the actual target receives the event. The last stage is the bubbling stage, which can also respond to events at this stage.
Taking the previous HTML page as an example, the sequence of triggering events:

Capture phase

  1. Document
  2. Element html
  3. Element body

Bubbling stage
4. Element div
5. Element body
6. Element html
7. Document

In the DOM event stream, the actual target (div element) will not receive events during the capture phase. This means that during the capture phase, the event stops after document to html to body. The next stage is the "at target" stage, so the event div occurs and is treated as part of the bubbling stage in the event processing. Then, the bubbling stage occurs and the event propagates back to the document.

IE8 and earlier versions do not support DOM event streaming, even if the "DOM2 level event" rule clearly requires that the capture phase will not involve event targets, but IE9, Safari, Chrome, Opera9.5 and later versions will trigger event objects during the capture phase event. The result is two opportunities to manipulate events on the target object.

Event delegation

The solution to the problem of "too many event handlers" is event delegation.
Event delegation takes advantage of event bubbling. You can manage all events of a certain type by specifying an event handler. For example, the click event will bubble up to the document level. We specify an onclick event handler for the entire page without having to add an event handler to each shell layer element separately.

<ul>
	<li id="goSomewhere">Go somewhere</li>
	<li id="doSomething">Do something</li>
	<li id="sayHi">Say Hi</li>
</ul>

According to the traditional approach, you need to add 3 event handlers for them. To
use event delegation, you only need to add an event handler at the highest possible level in the DOM tree.

var list = document.getElementById("myList");
EventUtil.addHandler(list,"click",function(event){
	event = EventUtil.getEvent(event);
	var target = EventUtil.getTarget(event);
	switch(target.id){
		case "doSomething":
			document.title = "I change the document's title";
			break;
		case "goSomewhere":
			location.href = "http://baidu.com"
			break;
		case "sayHi":
			alert("Hi");
			break;
	}
})

Since all list items are child nodes of this element, and their events will bubble, the click event will eventually be processed by this function, the event target is the clicked list item, so you can decide to take it by checking the id attribute Proper operation. Events suitable for event delegation technology: click, mouseup, keydown, keyup

Remove event handler

Whenever an event handler is assigned to an element, a connection is established between the running browser code and the JavaScript code that supports page interaction. The more such connections, the slower the page execution. Event delegation limits the number of connections. In addition, removing event handlers when they are not needed is also a solution to this problem.
Leaving out-of-date "empty event out programs" in memory is also the main cause of web application memory and performance issues.
Two situations cause the above problems: 1. When removing elements with event handlers from the document, it may be through pure DOM operations, for example: removeChild (), replaceChild () method, but more often occurs When replacing a part of the page with innerHTML, if the element innerHTML with the event handler is deleted, it is added to the element. example:

<div id="myDiv">
	<input type="button" value="Click Me" id="mybutton">
</div>
<script type="text/javascript">
	var btn = document.getElementById("myBtn");
	btn.onclick = function(){
		//先执行某些操作
		btn.onclick = null;//手工移除事件处理程序
		document.getElementById("myDiv").innreHTML = 'Processing ...';
		}
	}
</script>

Setting innerHTML on the div element can remove the button, but the event handler still maintains a reference relationship with the button. Some browsers (especially IE
) will not handle it properly in this case, and it is possible to keep references to elements and event handlers in memory. It is best to remove the event handler manually.

2. Another situation that leads to "empty event handlers". When written on the page,
if the event handlers are not cleaned up before the page is unloaded, they will stay in memory. Every time the page is loaded and the page is unloaded (may be switching back and forth or refreshing), the number of objects stuck in memory will increase because the memory occupied by the event handler has not been released.

The best practice is to remove the event handler through the onunload event handler before the page is unloaded. As long as things are added through the onload event handler, finally they must be removed through the onunload event handler.

Event handler

An event is a certain action performed by the user or the browser itself. click, load and mouseover are all event names. The function that responds to an event is called an event handler (or event listener). The name of the event handler is switched with "on", so the event handler for the click event is onclick.

HTML event handler

Each event supported by an element can be specified using an HTML specific name with the same name as the corresponding event handler. This feature value should be executable JavaScript code.

<input type = “button” value = “Click me” οnclick = “alert ('clicked');”> When you
click this button, an alert box will be displayed. This operation is done by specifying the onclick feature and adding some JavaScript code It is defined as its value. This value is JavaScript because you cannot use unescaped HTML syntax characters.
Event handlers defined in HTML can contain specific actions to be performed, and can also call scripts defined elsewhere on the page. Example:
<input type = “button” value = “Click me” οnclick = “show ()”>
This specifies that the event handler has some unique features. First, this creates a function that encapsulates the attribute value of the element. There is a local variable event in this function, which is the event object.
<input type = “button” value = “Click me” οnclick = “alert (event, type)”>
Through the event variable, you can directly access the event object. This value is equal to the target element of the event. (Inside the function)

There are two disadvantages to specifying event handlers in HTML. ① Time difference problem ② The scope chain of the extended event handler will cause different results in different browsers. ③ HTML and JavaScript code are tightly coupled
① Because the user may trigger the corresponding event as soon as the HTML element appears on the page, but the event handler at that time may not yet have the execution conditions.

DOM0 level event handler

The traditional way of specifying event handlers via JavaScript is to assign a function to the attributes of an event handler. The browser is still supported so far. Reason 1. Simple. 2. Advantages of cross-browser
To use JavaScript to specify the event handler, you must first obtain a reference to the object you want to operate.
Each element (including window and document) has its own event handler attributes. Example: onclick
sets the value of this attribute to a function, you can specify the event handler. example

var btn = doxument.getElementById("myBtn");
btn.onclick = function(){
	alert("clicked");
}
使用DOM0级方法指定的事件处理程序被认为是元素的方法。这时候的事件处理程序是在元素的作用域中运行,程序中的this引用当前元素。例:
var btn = document.getElementById("myBtn");
btn.onclick = function(){
	alert(this.id);
}
btn.onclick = null;//删除事件处理程序

DOM2 level events

Two methods are used to handle the operation of specifying and deleting event handlers: addEventLister () and removeEventListener (). All DOM nodes contain these two methods, three parameters: the name of the event to be processed, as a function of the event handler and a Boolean value. true, call handler in the capture phase, false, bubbling
var btn = document.getElementById (“myBtn”);
bn.addEventListener (“click”, function () {alert ( this.id )}, false);
Benefits: yes Add multiple event handlers. example:

var btn = document.getElementById("myBtn");
btn.addEventListener("click",function(){alert(this.id);}.false);
btn.addEventListener("click",function(){alert("Hello World");}.false);

Triggered in sequence
can only be removed using removeEventListener (), the parameters passed in when removed are the same as those added. This means that anonymous functions added via addEventListener () cannot be removed.

var btn = document.getElementById("myBtn");
var handler = function(){alert(this.id)};
btn.addEventListener("click",handler,false);
btn.removeEventListener("click",hander,false);//有效

In most cases, the event handler is added to the bubbling phase of the event flow, which maximizes compatibility with various browsers. Finally, the event handler is added to the capture phase only when the event needs to be intercepted before it reaches the target.

IE event handler

attachEvent () and datachEvent (). Two parameters: event handler name, event handler function
var btn = document.getElementById ("myBtn");
btn.attachEvent ("onclick", function () {alert ("clicked")}); // First One parameter is that onclick
is using the attachEvent () method, the event handler will run in the global scope, this is equal to window.
The attachEvent () method can also be used to add multiple event handlers to an element. The reverse order is triggered.
Provide the same parameters. Use detchEvent () to remove attachEvent ()

var btn = document.getElementById("myBtn");
var handler = function(){alert("clicked")};
btn.attachEvent("onclick",handler);
btn.detchEvent("onclick",handler);//移除事件处理程序

Cross-browser event handler

To ensure that the processed code is consistent in most browsers, only the bubbling stage needs to be concerned.
The first method to be created is addHandler (). Its responsibility is to use DOM0 level method, DOM2 level method, and IE method to add events as appropriate. This method belongs to an object called EventUtil.
3 parameters: the element to be operated, the event name and the event handler function
Use the EventUtil object as shown below (see page 354 for details)

var btn = document.getElementById("myBtn");
var handler = function(){
	alert("clicked");
}
Event.addHandler(btn,"click",handler);
Event.removeHandler(btn,"click",handler);

Event object

When an event on the DOM is triggered, an event object event is generated, and this object contains all information related to the event. Including the elements that caused the event, the type of event, and other information related to the specific event

Event object in DOM

DOM-compatible browsers will pass an event object into the event handler, regardless of DOM0, DOM2 level will pass in the event object

var btn = document.getElementById("myBtn");
btn.onclick = function(){
	alert(event.type);
}//click
btn.addEventListener("click",function(event){alert(event.type)},false);//"click"

Inside the event handler, the object this is always equal to the value of currentTarget, and target contains only the actual target of the event currentTarget: the element whose event handler is currently processing the event.
target: event target

document.body.onclick = function(event){
	alert(event.currentTarget === document.body);//true
	alert(this === document.body);//true
	alert(event.target === document.getElementById("myBtn"));//true
}

The event handler is registered on the document.body element, and the real goal of click is the button element.
When you need to handle multiple events through a function, you can use the type attribute.

To prevent the default behavior of specific events, you can use the preventDefalut () method.
Only events with the cancaelable property set to true can use preventDefalut () to cancel the default behavior.
The stopPropagation () method is used to immediately stop the propagation of events in the DOM hierarchy, that is, to cancel further event capture or bubbling.
example:

var link = document.getElementById("myLink");
link.onclick = function(event){
	event.preventDefault();
}
var btn = document.getElementById("myBtn");
btn.onclick = function(event){
	alert("clicked");
	event.stopPropagation();
}

The eventPhase attribute of the event object can be used to determine where the event is currently in the event flow.
event.eventPhase 1. Capture phase 2. Event handler is on target object 3. Bubbling phase

Event object in IE

When an event handler is added to a DOM-level method, the event object exists as a property of the window object

btn.onclick = function(){
	var event = window.event;
	alert(event.type);//"clicl"
}

If attachEvent () is added, then an event object will be passed into the event handler function as a parameter.
btn.attachEvent ("onclick", function (event) {alert (event.type)}) // click
event.srcElement Event target (same function as the target in DOM)
returnValue is false to cancel the default behavior, window.event / event .returnValue = false;
cancelBubble stop event bubbling window.event / event.cancelBubble = true;

Cross-browser event object

The front EventUtil object is enhanced
getEvent (): returns a reference to the event object event = EventUtil.getEvent (event); // DOM-> event IE-> window.event
getTarget (): returns the target of the event var target = EventUtil.getTarget (event);
preventDefailt (): The default behavior of the cancel event is to detect whether there is a preventDefault () call. If there is no call, returnValue is set to false

link.onclick = function(event){
	event = EventUtil.getEvent(event);
	EventUtil.preventDefault(event);
}

stopPropagation (): Stop bubbling, try to use DOM method to prevent, otherwise use cancelBubble


This article is from the summary of "JavaScript Advanced Programming"

Published 17 original articles · praised 0 · visits 768

Guess you like

Origin blog.csdn.net/CandiceYu/article/details/89889155