0

이벤트를 사용하여 자바 스크립트와 TypeScript 모듈간에 통신하려면 다음 서비스를 구현했습니다. 이것은 정상적으로 작동하지만 이벤트를 전송하는 것 이외에 적어도 이벤트에 따라 개체를 보내고 싶습니다. 그러나 나는 어떻게 시작해야할지 모른다. 어떤 힌트?TypeScript 및 JavaScript : 내용이있는 이벤트를 사용하여 통신

export interface IEventNotifcationService { 
    subscribe(event: MyEvent, callback:() => void); 
    emit(event: MyEvent); 
} 

export class EventNotifcationService implements IEventNotifcationService { 

    static serviceId = 'myServiceID'; 

    callbacks: { [key: number]: (() => void)[] } = {}; 

    constructor(private $timeout: ng.ITimeoutService) { 
     for (const event in MyEvent) { 
      this.callbacks[event] = []; 
     } 
    } 

    subscribe(event: MyEvent, callback:() => void) { 
     this.callbacks[event].push(callback); 
    } 

    emit(event: MyEvent) { 
     for (const callback of this.callbacks[event]) { 
      this.$timeout(callback, 0); 
     } 
    } 
} 

export enum MyEvent { 
    A = 'A', 
    B = 'B', 
    C = 'C' 
} 
+0

'15'이' –

답변

1

subscribeemit을 업데이트해야합니다. 여기

subscribe(event: MyEvent, callback:() => void) { 
     this.callbacks[event].push(callback); 
    } 

emit(event: MyEvent) { 
     for (const callback of this.callbacks[event]) { 
      this.$timeout(callback(event), 0); 
     } 
    } 

let listener = (event) => { 
    console.log('event occurred. data from the event:', event); 
} 

service.subscribe(listener) 
+0

int' 좋아 덕분에, 어떻게 그때 가입자 측에서 데이터를 검색 할 수 있습니다 콜백 정의하는 것 방법은? –

+0

'callback' 정의에 인수를 추가하여'subscribe'에 전달하면 콜백이 데이터에 액세스 할 수 있고 액세스 할 수 있습니다. – Val

+0

아하나. 따라서 제 경우에는 콘텐츠와 같은 추가 인수를 추가 할 것입니다. 고마워. –