因为厂商、版本等的差异导致的兼容性问题,CustomEvent这个对象并不是所有浏览器都支持,官方给了一个这样的方法用作兼容
(function(){
try{
// a : While a window.CustomEvent object exists, it cannot be called as a constructor.
// b : There is no window.CustomEvent object
new window.CustomEvent('T');
}catch(e){
let CustomEvent = function(event, params){
params = params || { bubbles: false, cancelable: false, detail: undefined };
let evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
})();
至于构造和触发事件的方法的话,我们可以自己写个
let publishCustomEvent = async ( eventName, eventParam , domElement) => {
if ( domElement instanceof EventTarget){
let customEvent = new CustomEvent(eventName, {detail:eventParam});
domElement.dispatchEvent(customEvent);
console.log(eventName+" pubed")
}
}
至于监听方的就addEventListener方法了,这个太普遍了,就不再赘述了。
发表评论