|
当我们发送(dispatch)自定义事件,我们需要设置 bubbles 和 composed 属性都为 true 以使其冒泡并从组件中冒泡出来。
例如,我们在 div#outer shadow DOM 内部创建 div#inner 并在其上触发两个事件。只有 composed: true 的那个自定义事件才会让该事件本身冒泡到文档外面:
<div id="outer"></div>
<script>
outer.attachShadow({mode: 'open'});
let inner = document.createElement('div');
outer.shadowRoot.append(inner);
/*
div(id=outer)
#shadow-dom
div(id=inner)
*/
document.addEventListener('test', event => alert(event.detail));
inner.dispatchEvent(new CustomEvent('test', {
bubbles: true,
composed: true,
detail: "composed"
}));
inner.dispatchEvent(new CustomEvent('test', {
bubbles: true,
composed: false,
detail: "not composed"
}));
</script>
|
|