Статьи

Internet Explorer 8 — исправьте обработку событий или не выпускайте ее

Что-то, что беспокоило веб-разработчиков в течение долгого времени, это собственная реализация обработки событий в Internet Explorer. В IE 8 это действительно должно идти.

Фон обработки событий

Основная проблема заключается в том, что, как и во многих других случаях, существует один стандартизированный способ обработки событий, а затем есть специальный, реализованный Microsoft в Internet Explorer.

DOM Level 2 Спецификация событий

13 ноября 2000 года была выпущена спецификация событий уровня 2 объектной модели документа ( DOM ) . По сути, вы используете метод, вызываемый addEventListenerдля добавления события к элементу, например так:

document.addEventListener("mousemove", trackMouse, false);
function trackMouse (evt) {
// The evt parameter is a local event object
}
document.addEventListener("mousemove", function (evt) {
// Track mouse movement
}, false);

Первый параметр — это имя события без префикса «on», второй — ссылка на функцию или анонимная функция, а третий — фаза захвата (т. Е. Если событие должно быть перехвачено, исходящее из родительского элемента или при всплывающем окне). от дочернего элемента или самого себя).

Реализация событий Internet Explorer

Microsoft давно решила пойти своим путем и вместо этого использовать нечто, называемое attachEvent. Приведенный выше пример будет выглядеть так с кодом, адаптированным для IE:

document.attachEvent("onmousemove", trackMouse);
function trackMouse (evt) {
// The evt parameter isn't available here, just the
// one global event object in Internet Explorer
}
document.attachEvent("onmousemove", function (evt) {
// Track mouse movement
});

Первый параметр — это имя события, но с префиксом «on», а второй — ссылка на функцию или анонимная функция.

Обработка событий Microsoft полна недостатков, среди которых некоторые из наиболее серьезных:

  • Всего один глобальный объект события вместо локальных объектов на событие.
  • При использовании attachEventметода ключевое слово thisв функции обработки событий относится к windowобъекту, а не к событию HTML, на котором оно фактически произошло.
  • Нет поддержки для фазы захвата.
  • Другой синтаксис, требующий префикса «on» для рассматриваемого события.

It has actually been so bad, that there was a competition online called the addEvent() recoding contest, to find the most suitable approach to get a common syntax and fixes for the IE bugs. When hobby web developers have to fix the faulty native implementation in a web browser, something is really really wrong.

What happens with Internet Explorer 8?

Every web browser has had proper event handling since about 2001, whereas Microsoft was already back then stuck with their beast of shame, IE 6. Fine, I’ll live with that, However, that they didn’t fix this in IE 7, since it’s one of the major scripting flaws in IE, was beyond me.

However, for IE 8, they said, they were add and repair a lot of JavaScript features. So ok, I waited. And the first IE 8 beta came along and, lo and behold, it even had support for the Selectors API (a working draft from December 2007)! Great, finally, I thought, Internet Explorer is catching up to the rest of the world.

But then I tested it for a while longer, and I soon realized, to my horror, that they had omitted standardized event handling in IE 8 as well! Again! Outrageous!

Microsoft’s take

What’s very interesting, and at the same time scary, is that if you dig a little, there was a bug report for lack of support for addEventListener in Internet Explorer 8, but it was closed with the wonderful motivation “by design”.

By design? Crap, by design? I always thought they knew of their shortcomings and acknowledged them, but were to fix them eventually — however, that statement is rather spitting in the face of developers, openly stating that they know it sucks, and that’s just the way they want it.

Fix it, or don’t release it

I think Microsoft should realize that web developers, although angered, have had a lot of patience with Internet Explorer. Lots of things were missing with IE 7, but people said, “sure, at least they’re trying now”. I felt the same way, they showed that they actually intended to make things better and were about to try to finally deliver a working product.

Lots of famous bloggers and developers, not the very least least JavaScript developers, have supported them, spoken for them and defended them along the way, stating that they’re getting there, one step at a time. But surely, even they must have had enough by now?

When Microsoft intentionally continue to neglect a W3C recommendation from 2000, but implement features from just a draft from 2007, what kind of message do they send out? Personally, I’ve had it.

Fix event handling in Internet Explorer 8, or don’t release it.