We have a component dynamically mounted inside a shadow DOM which communicates by the main DOM via events.
Can callbacks be sent via events?
Can the script inside the shadow DOM do undesirable things like pollute the global js namespace of the main DOM, taking into account callbacks?
(I believe the answers are "probably" and "probably not" respectively, but this is currently something of a debate. I'll update this question with the answers we find if we get there before anyone else, although it might be a while before we can find the resource and I feel like this would be a useful question for future explorers since my googling has failed).
My answers would be:
event.detail.callback
) GlobalVariable
<my-element id=ONE><button>Click One</button></my-element> <my-element id=TWO><button>Click Two</button></my-element> <script> let GlobalVariable = 0; window.customElements.define('my-element', class extends HTMLElement { constructor() { super().attachShadow({mode:'open'}).innerHTML = `<slot></slot>`; let report = (evt) => document.body.append( document.createElement("br"), GlobalVariable++, " - ", `${this.id} received: ${evt.type} - detail: ${JSON.stringify(evt.detail)} `, evt.detail.callback && evt.detail.callback(this.id) // not for 'click' event ); window.addEventListener('greet', report); // Custom Event window.addEventListener('click', report); // button click this.onclick = () => window.dispatchEvent(new CustomEvent('greet', { bubbles: true, composed: true, detail: { fromid: this.id, callback: this.callback.bind(this) } })); } callback(payload){ return `${this.id} executed callback function(${payload})`; } }); </script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.