3

I'm having trouble passing an event from jQuery to JavaScript. I am setting the JS event listener first and then firing the jQuery event from an external file, but the listener never gets triggered. Here's some code:

Listener

<script type="text/javascript">
document.addEventListener('readyToPlay', loadLibs);

function loadLibs() {
    alert('success');
}

</script>
<script src="/assets/js/plugins/co/co.js" type="text/javascript"></script>

Included File - The alert returns (function), which means jQuery is loaded

function init() {
    alert(typeof jQuery);
    $(document).trigger('readyToPlay');
}

I am thinking the issue might be caused by referencing document in the external file, but I'm not sure how to get around that.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

2

You can't use jQuery but you can fire it in Vanilla JS

function init() {
  var event= new CustomEvent('readyToPlay',[]);
  document.dispatchEvent(event);
}
gbalduzzi
  • 9,356
  • 28
  • 58
  • 1
    Thanks, this worked for me. Still, shouldn't jQuery events be pretty much the same as JavaScript? – Vladislav Dimitrov Sep 03 '15 at 07:55
  • Here the only reason i found, i'm not a real expert of jQuery http://stackoverflow.com/questions/10885009/jquery-trigger-not-firing-with-bind-or-on-for-custom-events – gbalduzzi Sep 03 '15 at 07:59
  • @VladislavDimitrov, your answer might be here: http://stackoverflow.com/a/41727891/1431728 and also: http://stackoverflow.com/a/18901932/1431728 – JohnK May 03 '17 at 21:36