Home > Web Front-end > JS Tutorial > JavaScript creates a cross-browser event handling mechanism [Produced by Blue-Dream]_javascript skills

JavaScript creates a cross-browser event handling mechanism [Produced by Blue-Dream]_javascript skills

WBOY
Release: 2016-05-16 18:23:21
Original
1224 people have browsed it

It is easier to solve compatibility problems by using class libraries. But what is the mechanism behind it? Let’s explain it bit by bit.

First of all, DOM Level2 defines two functions addEventListener and removeEventListener for event processing, both of which come from the EventTarget interface.

Copy code The code is as follows:

element.addEventListener(eventName, listener, useCapture);
element .removeEventListener(eventName, listener, useCapture);

The EventTarget interface is usually implemented from the Node or Window interface. It is also the so-called DOM element.
For example, window can also add listeners through addEventListener .
Copy code The code is as follows:

function loadHandler() {
console.log ('the page is loaded!');
}
window.addEventListener('load', loadHandler, false);

Removing the listener is also easy to do through removeEventListener, Just note that the removed handle and the added handle refer to a function.
window.removeEventListener('load', loadHandler, false);

If we live in a perfect world. Then estimate the event The function ends here.
But this is not the case. Because IE is unique. The two functions attachEvent and detachEvent are defined through MSDHTML DOM to replace addEventListener and removeEventListener.
There are many differences between the functions, which makes the entire The event mechanism has become extremely complex.
So what we have to do is actually to deal with the differences in event processing between IE browsers and w3c standards.

Add monitoring and To remove the listener, you can write
Copy code The code is as follows:

function loadHandler() {
alert('the page is loaded!');
}
window.attachEvent('onload', loadHandler); // Add listener
window.detachEvent('onload', loadHandler); / / Remove monitoring

From the surface, we can see two differences between IE and w3c:
1. There is an "on" prefix in front of the event.
2. The third parameter of useCapture has been removed.
In fact, the real differences are far more than these. We will continue to analyze them later. So for these two differences, we can easily abstract a common function
Copy code The code is as follows:

function addListener(element, eventName, handler) {
if (element. addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent('on' eventName, handler);
}
else {
element['on' eventName] = handler;
}
}
function removeListener(element, eventName, handler) {
if (element.addEventListener) {
element.removeEventListener(eventName, handler, false);
}
else if (element.detachEvent) {
element.detachEvent('on' eventName, handler);
}
else {
element['on' eventName] = null;
}
}

There are two things to note about the above function:
1. First It is best to measure the w3c standard for this branch first. Because IE is gradually getting closer to the standard. The second branch monitors IE.
2. The third branch is reserved for neither supporting (add/remove) EventListener nor (attach) /detach)Event browser.

Performance Optimization
For the above function, we use "runtime" monitoring. That is, each binding event requires branch monitoring. We can Change to "before running" to determine the compatible function. There is no need to monitor every time.
In this way, we need to use a DOM element to detect in advance. Here we choose document.documentElement. Why not use document.body? Because document .documentElement already exists when the document is not ready. And document.body does not exist before it is ready.
In this way, the function is optimized to
Copy code The code is as follows:

var addListener, removeListener,
/* test element */
docEl = document.documentElement;
// addListener
if (docEl.addEventListener) {
/* if `addEventListener` exists on test element, define function to use `addEventListener` */
addListener = function (element, eventName, handler) {
element.addEventListener(eventName, handler, false);
};
}
else if (docEl.attachEvent) {
/* if `attachEvent` exists on test element, define function to use `attachEvent` */
addListener = function (element, eventName, handler) {
element.attachEvent('on' eventName, handler);
};
}
else {
/* if neither methods exists on test element, define function to fallback strategy */
addListener = function (element, eventName, handler) {
element['on' eventName] = handler;
};
}
// removeListener
if (docEl.removeEventListener) {
removeListener = function (element, eventName, handler) {
element.removeEventListener(eventName, handler, false);
};
}
else if (docEl.detachEvent) {
removeListener = function (element, eventName, handler) {
element.detachEvent('on' eventName, handler);
};
}
else {
removeListener = function (element, eventName, handler) {
element['on' eventName] = null;
};
}

这样就避免了每次绑定都需要判断.
值得一提的是.上面的代码其实也是有两处硬伤. 除了代码量增多外, 还有一点就是使用了硬性编码推测.上面代码我们基本的意思就是断定.如果document.documentElement具备了add/remove方法.那么element就一定具备(虽然大多数情况如此).但这显然是不够安全.
不安全的检测
下面两个例子说明.在某些情况下这种检测不是足够安全的.
复制代码 代码如下:

// In Internet Explorer
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
if (xhr.open) { } // Error
var element = document.createElement('p');
if (element.offsetParent) { } // Error

如: 在IE7下 typeof xhr.open === 'unknown'. 详细可参考feature-detection
所以我们提倡的检测方式是
复制代码 代码如下:

var isHostMethod = function (object, methodName) {
var t = typeof object[methodName];
return ((t === 'function' || t === 'object') && !!object[methodName]) || t === 'unknown';
};

这样我们上面的优化函数.再次改进成这样
复制代码 代码如下:

var addListener, docEl = document.documentElement;
if (isHostMethod(docEl, 'addEventListener')) {
/* ... */
}
else if (isHostMethod(docEl, 'attachEvent')) {
/* ... */
}
else {
/* ... */
}

丢失的this指针
this指针的处理.IE与w3c又出现了差异.在w3c下函数的指针是指向绑定该句柄的DOM元素. 而IE下却总是指向window.
复制代码 代码如下:

// IE
document.body.attachEvent('onclick', function () {
alert(this === window); // true
alert(this === document.body); // false
});
// W3C
document.body.addEventListener('onclick', function () {
alert(this === window); // false
alert(this === document.body); // true
});

这个问题修正起来也不算麻烦
复制代码 代码如下:

if (isHostMethod(docEl, 'addEventListener')) {
/* ... */
}
else if (isHostMethod(docEl, 'attachEvent')) {
addListener = function (element, eventName, handler) {
element.attachEvent('on' eventName, function () {
handler.call(element, window.event);
});
};
}
else {
/* ... */
}

We only need to use a wrapper function. Then use call to re-correct the pointer of the handler internally. In fact, everyone should have noticed that there is also a problem that has been secretly corrected here. The event under IE is not passed through the first function. , but left in the global world. So we often write code like event = event || window.event. We have also made corrections here.
Corrected these major problems. Our function looks like It is much more robust. We can pause for a while and do a simple test. Three points of testing
1. Compatibility across browsers 2. Compatibility pointed by this pointer 3. Compatibility in event parameter passing.

The test code is as follows:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template