|
1, Event bubbling
To understand the event bubbling, you have to know the event flow. Flow of events described are from the order page to receive events, such as the following code:
< Body>
< Div>
click me!
< / Div>
< / Body>
If within the body and are registered div click event listeners, and later clicked div region, the first response is body or div first response? Interestingly, when the browser development team IE and Netscape proposed the concept almost exactly the opposite of the event flow. IE event is an event stream bubbling streams, Netscape proposed event is an event stream capture stream.
IE event is called event bubbling stream that is received by the most specific element when the event starts, then progressively spread upward to the relatively non-specific node (the document). As the code, click click event like this spread: div-> body-> html-> document (although I did not write html elements, but still there is a default on the page)
All modern browsers support event bubbling, but there are some nuances. IE5.5 and earlier in the event bubbling skipped < html> element (skip document directly from the body). IE9, ff, chrome and safari will be an event has been bubbling to the window object.
2, event capture
Netscape team has put forward an alternative flow of events - event capture. Event capture thoughts are less specific nodes should receive the earlier event, but the most specific nodes should receive the final event, if still above code example: document-> html-> body-> div.
While event capture is only supported Netscape event flow model, but IE9, Safari, chrome, opera and ff currently support this event flow model. Although "DOM2-level event" Compliant event should start spread from document object, but these browsers are beginning to capture events from the window object.
Because older versions of browsers do not support event capture, so we recommend using event bubbling.
3, DOM event flow
"DOM2 level event" provides event stream consists of three phases: the capture phase of the event, at the target and event bubbling phase. Or the above code as an example, click div element will trigger events in the following order: document-> html-> body-> div-> body-> html-> document.
In the DOM event flow, the actual goal (div) during the capture phase will not receive the event. This means that during the capture phase of the event to the body to stop, the next stage is the "in goal" stage, so the event occurs on div, and in the event processing is seen as part of the bubbling phase. Then, bubbling phase occurs, the event has spread back to the document. However, most browsers support the DOM event flow have achieved a specific behavior: even if "DOM2-level event" specification explicitly require the capture phase does not involve the target event, but IE9, safari, chrome, ff and opera9.5 and higher version will trigger event object during the capture phase, the result is to have the opportunity to operate in the above two audiences. (IE9, opera, ff, chrome and Safari support the DOM event flow, IE8 and earlier versions do not support DOM event flow).
4, the event handler
In response to an event is called an event handler function.
DOM0 level event handler is very simple, onclick is common DOM0 level event handler will only be processed in the bubbling phase.
The "DOM2-level event" defines two methods for processing operations specify and delete event handlers: addEventListener () and removeEventListener (), all DOM nodes contain these two methods, and they accept three parameters: event name to be treated as a function of the event handler and a Boolean value. Finally, this boolean parameter if it is true, that in the event handler is called the capture phase; if it is false, indicating that the call in the bubbling phase. Benefits DOM2-level approach is to add an event handler can add multiple event handlers, will be processed in accordance with the order of addition (either capture or bubbling). This is why DOM0 level events compatible with all browsers, but we still want to use one of the reasons DOM2.
var div = document.getElementById ( 'myDiv');
div.addEventListener ( 'click', function () {
console.log (this.id);
}, True);
div.addEventListener ( 'click', function () {
console.log ( 'hello world');
}, True);
The IE Unlike DOM, it has its own method: attachEvent () and detachEvent (), these methods accept the same two arguments: the name of the event handler and event handler function. Since IE8 and earlier versions only support event bubbling, so by attachEvent () to add an event handler will be added to the bubbling phase (so no third argument).
var div = document.getElementById ( 'myDiv');
div.attachEvent ( 'onclick', function () {
console.log ( 'hello world');
});
Note that the first parameter is onclick, rather than the standard DOM click. Use in IE attachEvent () The main difference between using DOM0 level approach is that the scope of the event handler, in the case DOM0 scale method, the event handler will run in the scope of their respective elements, and the use of attachEvent ( ) case of the method, the event handler to run the global scope, so this is equal to window (pay special attention to this point!). attachEvent () can also add multiple event handlers, but the execution sequence of events, and add the reverse order.
5, cross-browser event handler
Because of differences between browsers (IE fact, we know everything), so you need to write cross-browser event handler.
var EventUtil = {
addHandler: function (element, type, handler) {
if (element.addEventListener) {// DOM2
element.addEventListener (type, handler, false);
} Else if (element.attachEvent) {// IE
element.attachEvent ( 'on' + type, handler);
} Else {// DOM0
element [ 'on' + type] = handler;
}
},
removeHandler: function (element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener (type, handler, false);
} Else if (element.detachEvent) {
element.detachEvent ( 'on' + type, handler);
} Else {
element [ 'on' + type] = null;
}
}
};
6, the event object
When an event is triggered on the DOM, it will produce an event object event, this object contains all the information related to the incident. Pit father is the DOM event object and IE have a different play.
First is that the DOM:
var div = document.getElementById ( 'myDiv');
div.onclick = function (e) {
console.log (e.type);
};
div.addEventListener ( 'click', function (e) {
console.log (e.type);
}, False);
We should not familiar with the code above, we were achieved DOM0 grade level and DOM2 event object.
e has a lot of properties and methods, to mention here a few commonly used. target and currentTarget, target refers to the real target of the event, and currentTarget refers to the current goal is the use of target and we will do the event broker.
To prevent the default behavior of a particular event, we can use the preventDefault () method, for example, the default behavior of the link is being clicked navigates to its href specified url, if you want to stop this default behavior, so by linking onclick event handlers can cancel it:
var link = document.getElementById ( 'myLink');
link.onclick = function (e) {
e.preventDefault ();
};
Only cancelable property is set to true events, you can use preventDefault () to cancel the default behavior.
In addition, stopPropagation () method is used to immediately stop the event propagation in the DOM layer, cancel further event capturing or bubbling.
var div = document.getElementById ( 'myDiv');
div.onclick = function (e) {
console.log ( 'click!');
e.stopPropagation ();
};
document.body.onclick = function (e) {
console.log ( 'hello world');
};
The IE event objects are so useful:
var div = document.getElementById ( 'myDiv');
div.onclick = function () {
var e = window.e;
console.log (e.type);
};
div.attachEvent ( 'onclick', function (e) {
// You can also access by window.e
console.log (e.type);
});
IE in the event objects also have many properties and methods, such as srcElement and DOM is the same target properties, and returnValue property is equivalent to the DOM preventDefault () method, their role is to cancel the default behavior of a given event. As long as the value is set to false, you can prevent the default behavior. Accordingly, canceBubble property and the DOM stopPropagation () method of the same effect, because IE only supports bubbling, so it can only cancel event bubbling.
Cross-browser event object:
var EventUtil = {
getEvent: function (e) {
? Return e e: window.e;
},
getTarget: function (e) {
return e.target || e.srcElement;
},
preventDefault: function (e) {
if (e.preventDefault) {
e.preventDefault ();
} Else {
e.returnValue = false;
}
},
stopPropagation: function (e) {
if (e.stopPropagation) {
e.stopPropagation ()
} Else {
e.cancelBubble = true;
}
}
}
7, the event delegate
With the above as a basis, the event delegate should be very simple. What is an event delegate? On the "event handler too" solution to the problem is the event delegate. Use event bubbling event delegate to specify only one event handler, you can manage all events of a certain type. For example, click events are bubbling to the document level, which means that we can specify an onclick event handler for the entire page without having to click on each element to add an event handler, respectively.
For frequently cited examples, such as the following codes:
< Ul id = 'myLink'>
< Li id = 'a'> apple < / li>
< Li id = 'b'> banana < / li>
< Li id = 'c'> orange < / li>
< / Ul>
The desired effect is to click on each of the corresponding < li> option, alert word inside it, probably very simple:
var lis = document.getElementsByTagName ( 'li');
for (var i = 0, len = lis.length; i < len; i ++) {
lis [i] .onclick = function () {
alert (this.innerHTML);
};
}
But above code to bind the three events, we need to know that every event is bound to take up some memory, even worse, if during the execution of the code, has added a dynamic li, then it does not bind click event, and we also need to manually add! At this point, we can use technology event delegate:
var f = document.getElementById ( 'myLink');
f.onclick = function (e) {
console.log (e.target.innerHTML);
};
Well, is that simple! |
|
|
|