我有以下代码需要使用initEvent的最新替代方案进行重构:
let createdEvent = document.createEvent('Event');
createdEvent.initEvent(event);
document.dispatchEvent(createdEvent);
我尝试了以下方法:
let createdEvent = new Event('Event', { "bubbles": true, "cancelable": false });
createdEvent.addEventListener(event);
document.dispatchEvent(createdEvent);
我试图将事件侦听器添加到事件中。但这是行不通的。你能告诉我我哪里错了吗?
发布于 2022-10-04 18:22:35
我使用不推荐的createEvent
/initEvent
和CustomEvent
编写了两个事件调度器实现。这两个函数都采用类似的参数,但CustomEvent
允许将detail
参数作为选项传递。这可用于向接收事件侦听器发送数据。
const helloEl = document.querySelector('#hello');
const dispatchLegacyEvent = (eventName, element = document, options = {}) => {
const { bubbles = false, cancelable = false } = options;
const createdEvent = document.createEvent('Event');
createdEvent.initEvent(eventName, bubbles, cancelable);
element.dispatchEvent(createdEvent);
};
const dispatchCustomEvent = (eventName, element = document, options = {}) => {
const event = new CustomEvent(eventName, {
bubbles: options.bubbles ?? false,
cancelable: options.cancelable ?? false,
detail: options.detail
});
element.dispatchEvent(event);
};
helloEl.addEventListener('my-action', (e) => {
if (e.detail) {
console.log(`Ran ${e.detail} action!`);
} else {
console.log('Ran legacy action!');
}
});
dispatchLegacyEvent('my-action', helloEl);
dispatchCustomEvent('my-action', helloEl, { detail: 'custom' });
<div id="hello">Hello World</div>
注:有基于Event
的40多个(不推荐)事件接口。
发布于 2022-10-04 18:28:25
addEventListener
的参数必须是事件名,然后是回调函数。然后,必须将事件侦听器附加到DOM元素(文档或任何节点),而不是附加到事件对象。
let createdEvent = new Event('Event', {
"bubbles": true,
"cancelable": false
});
someHtmlElement.addEventListener(
"Event",
someEventHandlerCallback
);
someHtmlElement.dispatchEvent(createdEvent);
看看https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#example
https://stackoverflow.com/questions/73951805
复制相似问题