Event Type Property Lost in IE-8

I noticed a strange Javascript error that seems to be happening in Internet Explorer 8. Basically, on IE-8, if you have an event handler function that captures an event object in closure, an event property of the type "seems" to become invalid from -for closing.

Here is a simple piece of code that reproduces the error:

<html> <head> <script type="text/javascript"> function handleClickEvent(ev) { ev = (ev || window.event); alert(ev.type); window.setTimeout(function() { alert(ev.type); // Causes error on IE-8 }, 20); } function foo() { var query = document.getElementById("query"); query.onclick = handleClickEvent; } </script> </head> <body> <input id="query" type="submit" /> <script type="text/javascript"> foo(); </script> </body> </html> 

So basically what happens here in the handleClickEvent function is an ev event object. We call alert(ev.type) , and we see that the type of the event is "click". So far, so good. But then, when we capture the event object in the closure, and then call alert(ev.type) again from within the closure, Internet Explorer 8 errors now suddenly appear, saying "Member not found" due to the expression ev.type . It seems that the type property of the event object mysteriously disappeared after we committed the event object to close.

I tested this piece of code on Firefox, Safari, and Chrome, and none of them reported an error. But in IE-8, the event object seems somehow invalid after it is captured in closure.

Question : Why is this happening in IE-8, and is there a workaround?

+4
source share
1 answer

Yes, this is because the event data structure is a global variable in IE8, so it is overwritten by other events when they occur. If you want it to remain for closing, you will need to make an actual copy of the event data structure in the closing so that you can refer to a static copy, and not to a single global structure that is reused by IE8.

Creating a copy of the data structure consists of creating a new object and copying all the properties. If any properties themselves are objects or arrays, you should also make copies of them (just assigning them to a new object will assign links, not copies).

Or, if you only need type , just assign type local variable in the closure and just a link like this.

 function handleClickEvent(ev) { ev = (ev || window.event); // save copy of type locally so we can use it later in setTimeout() var type = ev.type; alert(type); window.setTimeout(function() { alert(type); }, 20); } 
+5
source

Source: https://habr.com/ru/post/1441863/


All Articles