Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross Browser compatible CustomEvent

I need to create a Custom Event which will pass some data to the event listener. I already created one like below

CustomEvent

var event = new CustomEvent('store', { 'detail': obj });
document.getElementById("Widget").dispatchEvent(event);

Listener

document.getElementById("Widget").addEventListener('store', function (e) {
  console.log(e.detail);
  document.getElementById("result").innerHTML = e.detail.name+"<br>"+e.detail.address;
}, false);

It is working fine in browsers such as Chrome and Firefox but not working in IE11. I am getting an error in IE:

Object doesn't support this action

CustomEvent is not working in IE.

How can I make this cross-browser compatible ? I don't want to use jQuery trigger() because the Listener might not be in a page having jQuery

like image 698
Sarath S Nair Avatar asked Jun 01 '16 10:06

Sarath S Nair


2 Answers

CoustomEvent constructor is not supported in IE11. you can use following pollyfill

(function () {

     if ( typeof window.CustomEvent === "function" ) return false;

     function CustomEvent ( event, params ) {
         params = params || { bubbles: false, cancelable: false, detail: undefined };
         var evt = document.createEvent('CustomEvent');
         evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
         return evt;
     }

     CustomEvent.prototype = window.Event.prototype;

     window.CustomEvent = CustomEvent;
})();

Copied from MDN

like image 200
Sandeeproop Avatar answered Oct 01 '22 03:10

Sandeeproop


Take a look to the "Can I use" page and what it says about the Custom Events.

http://caniuse.com/#feat=customevent

Specifically, read this quote:

While a window.CustomEvent object exists, it cannot be called as a constructor. Instead of new CustomEvent(...), you must use e = document.createEvent('CustomEvent') and then e.initCustomEvent(...)

like image 43
dlopez Avatar answered Oct 01 '22 01:10

dlopez