Skip to content

Commit

Permalink
chore(core): 页面变化时仅移除配置的事件
Browse files Browse the repository at this point in the history
  • Loading branch information
roymondchen committed Mar 29, 2023
1 parent 37045f7 commit 5eb3b0d
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions packages/core/src/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ class App extends EventEmitter {

public eventQueueMap: Record<string, EventCache[]> = {};

private eventList: { [name: string]: (fromCpt: Node, ...args: any[]) => void } = {};

constructor(options: AppOptionsConfig) {
super();

Expand Down Expand Up @@ -175,6 +177,7 @@ class App extends EventEmitter {
this.page.destroy();
this.page = undefined;
}
super.emit('page-change');
return;
}

Expand All @@ -189,6 +192,8 @@ class App extends EventEmitter {
app: this,
});

super.emit('page-change', this.page);

if (this.platform !== 'magic') {
this.bindEvents();
}
Expand Down Expand Up @@ -223,22 +228,27 @@ class App extends EventEmitter {
}

public bindEvents() {
if (!this.page) return;
Object.entries(this.eventList).forEach(([name, handler]) => {
this.off(name, handler);
});

this.removeAllListeners();
this.eventList = {};

if (!this.page) return;

for (const [, value] of this.page.nodes) {
value.events?.forEach((event) => this.bindEvent(event, `${value.data.id}`));
value.events?.forEach((event) => {
const eventName = `${event.name}_${value.data.id}`;
const eventHanlder = (fromCpt: Node, ...args: any[]) => {
this.eventHandler(event, fromCpt, args);
};
this.eventList[eventName] = eventHanlder;

this.on(eventName, eventHanlder);
});
}
}

public bindEvent(event: EventConfig | DeprecatedEventConfig, id: string) {
const { name } = event;
this.on(`${name}_${id}`, async (fromCpt: Node, ...args) => {
await this.eventHandler(event, fromCpt, args);
});
}

public emit(name: string | symbol, node: any, ...args: any[]): boolean {
if (node?.data?.id) {
return super.emit(`${String(name)}_${node.data.id}`, node, ...args);
Expand Down

0 comments on commit 5eb3b0d

Please sign in to comment.