簡體   English   中英

我可以將兩個不同的主機偵聽器包裝在一個 function in angular 2 中嗎

[英]Can I wrap two different host listeners in a single function in angular 2

我需要將 2 個不同的主機偵聽器包裝在一個 function 中,這樣我就可以在需要偵聽器時調用 function。

@HostListener('window:unload', ['$event'])
unloadHandler() {
  this.eventService.send({ name: 'onUnload' });
}

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander (event: Event){

  let confirmation = {
    message: undefined
  };
  this.eventService.send({ name: 'onBeforeUnload',data:confirmation });

}

現在我需要將它包裝在一個 function 中,如下所示,並且可以在需要時調用它 function

public enable(): any {
@HostListener('window:unload', ['$event'])
unloadHandler() {
  this.eventService.send({ name: 'onUnload' });
}

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander (event: Event){

  let confirmation = {
    message: undefined
  };
  this.eventService.send({ name: 'onBeforeUnload',data:confirmation });

}
}

這個問題已經回答了。 您可以將 1 個以上的 Hostlistener 設置為一個 function, 我可以使用多個 @hostlistener 或基於瀏覽器的事件嗎?

但是你 r 試圖做的是行不通的。 您不會自己調用具有 Hostlistener 的函數。 當主機檢測到這些事件時,這些功能會自動觸發。 因此,在您的情況下,就在選項卡/瀏覽器關閉之前調用 unload() 函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM