gpt4 book ai didi

javascript - TypeScript 和 JavaScript : Communicate using events with content

转载 作者:行者123 更新时间:2023-12-03 02:49:43 25 4
gpt4 key购买 nike

我已经实现了以下服务,以便使用事件在 Javascript 和 TypeScript 模块之间进行通信。这工作正常,但除了传输事件之外,我还想发送一个带有事件的对象,至少在某些情况下是这样。但是,我不知道如何开始。有什么提示吗?

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'
}

最佳答案

您应该更新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)

关于javascript - TypeScript 和 JavaScript : Communicate using events with content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com