0

All of this is happening for IE8.

Due to script import orders, I'm having a bit of code being executed before JQuery is loaded where I need to fire a custom event.

This event will be picked up later in another bit of code when I'm sure JQuery will have been loaded. So I'd like to use JQuery to pick up this event.

I saw this previously asked question: How to trigger a custom javascript event in IE8? and applied the answer, which worked, but when I'm trying to pick up the Event via JQuery, then nothing happens.

Here's what I've tried:

function Event() {}

Event.listen = function(eventName, callback) {
  if (document.addEventListener) {
    document.addEventListener(eventName, callback, false);
  } else {
    document.documentElement.attachEvent('onpropertychange', function(e) {
      if (e.propertyName == eventName) {
        callback();
      }
    });
  }
};

Event.trigger = function(eventName) {
  if (document.createEvent) {
    var event = document.createEvent('Event');
    event.initEvent(eventName, true, true);
    document.dispatchEvent(event);
  } else {
    document.documentElement[eventName] ++;
  }
};



Event.listen('myevent', function() {
  document.getElementById('mydiv-jquery').innerText = "myevent jquery";
});

$(document).on('myevent', function() {
  document.getElementById('mydiv-vanilla').innerText = "myevent vanilla";
});

Event.trigger('myevent');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mydiv-jquery">Nothing</div>
<div id="mydiv-vanilla">Nothing</div>

PS: The snippet doesn't seem to work properly in IE. Here's a jsfiddle that should be working.

Community
  • 1
  • 1
Antoine Combes
  • 1,444
  • 8
  • 13

1 Answers1

1

There are a few problems with this code.

  • You shadow the built-in window.Event without checking if it exists; this could cause problems for other scripts.

  • You don't preserve the this binding when calling the callback from your onpropertychange listener. You should apply the callback to the document rather than calling it directly so the behavior will be as close as possible to addEventListener.

  • You attempt to increment document.documentElement[eventName] while it is undefined. The first call will change the value to NaN, so onpropertychange should pick it up, but on subsequent calls it will remain NaN.

  • You make no attempt to have .on() recognize your Event.listen function, so naturally the code in Event.listen will never be executed from a listener attached with .on().

Have you tried using Andrea Giammarchi's CustomEvent shim?

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
  • Thank you for your answer. The problems you noticed are duly noted :) I'll be sure to correct those as soon as I can my hands on the code again. I did not know about this shim, so I'll check it out as well. As for your last point, would you have any lead on how to do such a thing ? – Antoine Combes Nov 07 '14 at 21:45