Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stay events reference is not updated on event swich #438

Merged
merged 2 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 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 @@ -601,10 +601,18 @@ export function make<T>(comps: CompList<T> = []): GameObj<T> {

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 handler with the new one
// old KEventController.cancel() => new KEventController.cancel()
KEventController.replace(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