1 回答

TA貢獻1890條經驗 獲得超9個贊
在組件本身上分派事件,bubble: true, composed: true
以便該事件將冒泡到任何監視它的地方。當您想要非常具體地擁有大量可預測性和共享狀態時,我的意思是這確實是所需的緊密耦合,那么只需在全局self
(即window
在瀏覽器中)。這里有一些隨機的例子,我希望有所幫助,他們所做的只是為了展示一個例子而相對無用??傮w想法是在有意義的情況下松散地耦合事物,事件只是傳遞與狀態更改相關的消息。組件始終可以是相當隔離的,無論它在什么上下文中運行,都可以單獨關注它對該信息的處理(準備和接收模型——這是功能模式高度適用的地方)。如果需要更多細節或令人困惑,請隨時將其拼寫出來,我們可以盡力提供幫助。
另請注意,因為我沒有設置任何 ShadowRoot,所以組合標志在此示例中根本沒有用處。
寬廣地:
全局:(其他上下文中的
self
同義詞window
或工人);這里協調旨在跨許多事物緊密耦合的事件——當需要非常具體的協調系統時,這是迄今為止最簡單的組織方案;對于這種情況,只需在此處偵聽并分派事件即可;connectedCallback
在和中添加和刪除事件偵聽器disconnectedCallback
。然后,不再需要通過冒泡或直接self.dispatchEvent('type', {detail:...})
冒泡等方式調度。節點:在樹的任何級別,當組件具有任何類型的任何狀態或事件時,處理場景并創建適當的消息作為 和
event.detail
合理的名稱作為event.type
,然后從處理該邏輯的節點分派它。其他節點(父節點等)可以監視事件event.bubble
,并且當從影子節點分派時,這些事件可以使用該composed:true
標志來允許事件在影子根之外繼續?;蛘咴撛乜梢蕴幚韮炔渴录⒎峙蛇m合該類型的新類型的事件和有效負載。
<my-global>my global </my-global>
<my-aye> aye (parent)
<my-bee> bee (child) </my-bee>
</my-aye>
<my-bee> bee </my-bee>
function eventdetails(event){
const {type, detail} = event;
console.log({type, detail, self:this, path: event.composedPath(), event});
}
customElements.define('my-global', class MyGlobalWatch extends HTMLElement{
constructor(){
super();
this.global = this.global.bind(this);
}
global(event){
eventdetails.call(this, event);
}
connectedCallback(){
self.addEventListener('global', this.global);
}
disconnectedCallback(){
self.removeEventListener('global', this.global);
}
});
customElements.define('my-aye', class MyAye extends HTMLElement{
constructor(){
super();
this.addEventListener('hi-aye', this.handle);
this.addEventListener('hi-bee', this.handle);
}
handle(event){
eventdetails.call(this, event);
if(event.type === 'hi-bee'){
self.dispatchEvent(new CustomEvent('global', {detail: event.detail, cancelable: true, composed: true, bubbles: false}));
}
}
});
customElements.define('my-bee', class MyBee extends HTMLElement{
constructor(){
super();
this.addEventListener('hi-aye', this.handle);
this.addEventListener('hi-bee', this.handle);
this.ticker = this.ticker.bind(this);
}
handle(event){
eventdetails.call(this, event);
}
ticker(){
// 3 events of the same type, different configuration
this.dispatchEvent(new CustomEvent('hi-aye', {detail: {payload:'> -composed +bubbles'}, cancelable: true, composed: false, bubbles: true}));
this.dispatchEvent(new CustomEvent('hi-aye', {detail: {payload:'> +composed +bubbles'}, cancelable: true, composed: true, bubbles: true}));
this.dispatchEvent(new CustomEvent('hi-aye', {detail: {payload:'> -composed -bubbles'}, cancelable: true, composed: false, bubbles: false}));
this.dispatchEvent(new CustomEvent('hi-bee', {detail: {stuff:'things'}, cancelable: true, composed: true, bubbles: true}));
this._timer = setTimeout(this.ticker, 1234);
}
connectedCallback(){
this.ticker();
}
disconnectedCallback(){
clearTimeout(this._timer);
}
});
添加回答
舉報