Skip to content

Commit

Permalink
fix: stay events reference is not updated on event swich
Browse files Browse the repository at this point in the history
  • Loading branch information
lajbel committed Oct 6, 2024
1 parent 6cf1290 commit 4906476
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
19 changes: 15 additions & 4 deletions src/game/make.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
type QueryOpt,
type Tag,
} from "../types";
import { type KEventController, KEventHandler, uid } from "../utils";
import { KEventController, KEventHandler, uid } from "../utils";

export function make<T>(comps: CompList<T> = []): GameObj<T> {
const compStates = new Map<string, Comp>();
Expand Down Expand Up @@ -596,15 +596,26 @@ export function make<T>(comps: CompList<T> = []): GameObj<T> {

for (const e of evs) {
obj[e] = (...args: [any]) => {
const ev = app[e]?.(...args);
let ev = app[e]?.(...args);
inputEvents.push(ev);

obj.onDestroy(() => ev.cancel());
obj.on("sceneEnter", () => {
ev.cancel();
// All app events are already canceled by changing the scene
// not neccesary -> ev.cancel();
inputEvents.splice(inputEvents.indexOf(ev), 1);
app[e]?.(...args);
// create a new event with the same arguments
const newEv = app[e]?.(...args);

// Replace the old event functions with the new ones
// old KEventController.cancel() => new KEventController.cancel()
KEventController.replace(ev, newEv);
// Save the reference to the new event so replace work every scene change
// There's always only 2 events connected, old and new
ev = newEv;
inputEvents.push(ev);
});

return ev;
};
}
Expand Down
12 changes: 11 additions & 1 deletion src/utils/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class KEventController {
/** If the event is paused */
paused: boolean = false;
/** Cancel the event */
readonly cancel: () => void;
cancel: () => void;

constructor(cancel: () => void) {
this.cancel = cancel;
Expand All @@ -51,6 +51,16 @@ export class KEventController {
ev.paused = false;
return ev;
}
static replace(oldEv: KEventController, newEv: KEventController) {
oldEv.cancel = () => newEv.cancel();
newEv.paused = oldEv.paused;
Object.defineProperty(oldEv, "paused", {
get: () => newEv.paused,
set: (p: boolean) => newEv.paused = p,
});

return oldEv;
}
}

export class KEvent<Args extends any[] = any[]> {
Expand Down

0 comments on commit 4906476

Please sign in to comment.