Javascript 侦听Web组件上的全局事件
我有一个main.js,它调用API并接收响应对象。在响应之后,我想触发自定义Web组件正在侦听的事件Javascript 侦听Web组件上的全局事件,javascript,dom-events,web-component,custom-events,Javascript,Dom Events,Web Component,Custom Events,我有一个main.js,它调用API并接收响应对象。在响应之后,我想触发自定义Web组件正在侦听的事件 makeRequest(request).then((response) => { // NOTE: the API in question returns a Promise, thus using 'then()' dispatchCustomEvent(response); }); let dispatchCustomEvent = (response) => {
makeRequest(request).then((response) => { // NOTE: the API in question returns a Promise, thus using 'then()'
dispatchCustomEvent(response);
});
let dispatchCustomEvent = (response) => {
console.log('dispatchCustomEvent called', response);
let myCustomEvent = new CustomEvent('package-ready',
{
bubbles: true,
composed: true,
detail: response
}
);
return document.dispatchEvent(myCustomEvent);
}
此事件在主文档中起作用。我已将侦听器附加到要测试的主文档,但在自定义组件上听不到它
从上面可以看到,我已经将侦听器连接到组件(使用this
)和它的影子根(出于测试目的)
在定义的web组件上听不到该事件。我认为这可能与事件捕获阶段有关(可能还会向我的自定义事件选项对象添加另一个标志)
我仍在学习Web组件的详细信息,但还没有弄明白这一点。如果有任何帮助,我将不胜感激!您正在
文档上发送事件。事件将永远不会到达组件,因为事件不会发送到页面上的每个元素
在捕获阶段,事件从document
向下移动到发送它的事件,然后气泡阶段沿着树的另一个方向移动,并从发送它的元素返回到document
您的组件需要将其事件侦听器添加到文档
,或者您的代码需要更改为以下内容:
makeRequest(request).then((response)=>{//注意:所讨论的API返回一个承诺,因此使用'then()'
调度自定义事件(响应);
});
让dispatchCustomEvent=(响应)=>{
log('调用dispatchCustomEvent',响应);
让myCustomEvent=new CustomEvent('package-ready',
{
泡泡:是的,
是的,
详情:答复
}
);
document.querySelectorAll('app-list').forEach(
el=>{
返回el.dispatchEvent(myCustomEvent);
}
);
}
详细说明见:
window.customElements.define('app-list',
class AppList extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
this.addEventListener('package-ready', e => console.log('package-ready heard on app-list', e.detail));
shadowRoot.addEventListener('package-ready', e => console.log('package-ready heard on app-list Shadow Root', e.detail));
}
}