const myEvent = new CustomEvent(typeName, option)
// create custom events
const catFound = new CustomEvent('animalfound', {
detail: {
name: 'cat'
}
});
const dogFound = new CustomEvent('animalfound', {
detail: {
name: 'dog'
}
});
// add an appropriate event listener
obj.addEventListener('animalfound', (e) => console.log(e.detail.name));
// dispatch the events
obj.dispatchEvent(catFound);
obj.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console**Polyfill(IE)**
/**
* CustomEvent constructor polyfill for IE
*/
(function () {
if (typeof window.CustomEvent === 'function') {
// 如果不是IE
return false;
}
var CustomEvent = function (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;
})();