3

In Chrome/Firefox I can attach my custom properties to an event object in one handler and read them in a different handler for the same event even if the event handling is bubbled up.

I cannot do the same in IE. My custom property is lost while event is bubbled up. Do you know if there's any solution or workaround to this?

The following is an example of that problem:

<div id="div1">
<input type="button" value="Foo" id="button1">
</div>

<script>

function attach(el, event, fn) {
  if (el.addEventListener) {
    el.addEventListener(event, fn);
  } else if (el.attachEvent) {
    el.attachEvent('on'+event, fn);
  }

}

attach(document.getElementById("button1"), 'click', function (event) {
event.abc = "done";
return true;
});

attach(document.getElementById("div1"), 'click', function (event) {
alert(event.abc);
return true;
});

</script>
mgamer
  • 13,580
  • 25
  • 87
  • 145
  • 1
    You are not even accessing the `event` object in IE. IE does not pass it to the event handler, it is only available via `window.event`. Try this first. – Felix Kling Sep 09 '11 at 12:55
  • @Felix I tried window.event but to no avail. I am pretty sure that event object is passed to the event handler though. – mgamer Sep 09 '11 at 12:59
  • IE8 is what I use and there's definitely an event object passed to the event handler. – mgamer Sep 09 '11 at 13:02
  • At the risk of sounding like a fanboy: this is why programmers who use jQuery (or something like it) never go back -- because it handles all these ugly browser incompatabilities for you. – Blazemonger Sep 09 '11 at 13:09
  • @mgamer check the [Microsoft documentation](http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx) - the function is **not** passed the event object. The symbol "event" is a property name on the `window` object. – Pointy Sep 09 '11 at 13:13
  • @Pointy substitute in my example "event" symbol with "e" and go ahead try for yourself – mgamer Sep 09 '11 at 13:18

1 Answers1

0

According with my test you cannot add property to event object in IE (IE8 tested).

Try next code:

attach(document.getElementById("button1"), 'click', function (ev) {
  //ev=ev||event;
  //ev.abc = "done";
  // next lines show you why you cannot save properties in event object
  var xx1=event;
  var xx2=event;
  alert(xx1===xx2); // // showed *false* in IE8, but expected *true*

  return true;
});

I am not sure but maybe, when event object is requested, IE8 always return new object, that contains same properties/values as previous requested.

Andrew D.
  • 8,130
  • 3
  • 21
  • 23