-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: RegisterEventForGamemode util function
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
/** | ||
* Pass an event that should be only registered when playing certain gamemodes. | ||
* | ||
* This function will register/unregister the provided events handler when gamemodes change. | ||
* | ||
* It returns a function that will clean up both event handlers. It's unlikely we'll ever need to use it, | ||
* so usually you can just discard it. | ||
* | ||
* @example | ||
* ```ts | ||
* // In the static initializer block for some panel's class, call the onUpdate function on this class | ||
* // whenever the 'HudProcessInput' event is fired, ONLY if the current gamemode is Gamemode.DEFRAG. | ||
* static { | ||
* RegisterEventForGamemodes( | ||
* [GameMode.DEFRAG], | ||
* 'HudProcessInput', | ||
* $.GetContextPanel(), | ||
* this.onUpdate.bind(this) | ||
* ); | ||
* } | ||
* ``` | ||
* @param gamemodes - Gamemodes to register the callback for. Handler is unregistered for any other modes. | ||
* @param event - Event name | ||
* @param context - Panel context | ||
* @param callbackFn - Event callback | ||
* @returns Cleanup function that unregisters both event handlers | ||
*/ | ||
function RegisterEventForGamemodes( | ||
gamemodes: number[], | ||
event: string, | ||
context: string | Panel, | ||
callbackFn: (...args: unknown[]) => void | ||
): () => void { | ||
let innerHandle: number | undefined; | ||
const outerHandle = $.RegisterForUnhandledEvent('LevelInitPostEntity', () => { | ||
// @ts-expect-error - TODO: Typings for this API | ||
if (!innerHandle && gamemodes.includes(GameModeAPI.GetCurrentGameMode())) { | ||
innerHandle = $.RegisterEventHandler(event, context, callbackFn); | ||
} else if (innerHandle) { | ||
$.UnregisterEventHandler(event, context, innerHandle); | ||
innerHandle = undefined; | ||
} | ||
}); | ||
|
||
return () => { | ||
if (innerHandle) { | ||
$.UnregisterEventHandler(event, context, innerHandle); | ||
} | ||
|
||
$.UnregisterForUnhandledEvent('LevelInitPostEntity', outerHandle); | ||
}; | ||
} |