2017-10-21 49 views
0

我想執行一些香草JavaScript代碼(在外部文件中),當發佈離子事件時。 但我不知道如何做到這一點。我想要這樣的東西。在香草中訂閱ionic 3事件Javascript

打字稿

this.event.publish('TestEvent',{data:123}); 

的JavaScript

document.addEventListener("TestEvent", function(data) { 
      alert('TestEvent'); 
}); 

回答

0

我猜你可能只是再次觸發事件上document

TS:

this.event.publish('TestEvent', {data:123}); 

const event = new CustomEvent('TestEvent', {detail: {data: 123}}); 
document.dispatchEvent(event); 

JS:

document.addEventListener('TestEvent', function (event) { 
    alert('TestEvent'); 
    console.log(event.detail.data); // prints 123 
}); 

更多關於MDN自定義事件:

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

+0

'的console.log(event.data);''顯示undefined' – shah

+0

抱歉,我的不好,會更新我的答案。您需要將有效載荷包裝到另一個對象中... –