From 451209f98c17e4b228d7a828662e4b72077fe55f Mon Sep 17 00:00:00 2001 From: David Date: Thu, 2 Jun 2022 16:32:28 -0700 Subject: [PATCH] feat(recs): add optional parameters to reaction and autorun systems adding optional options parameters object to defineReactionSystem and defineAutorunSystem so that in the future other parameters can be passed in without creating weird syntax problems of passing in undefined params lat-596 --- packages/recs/src/System.ts | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/recs/src/System.ts b/packages/recs/src/System.ts index 790e924045..826ddefe89 100644 --- a/packages/recs/src/System.ts +++ b/packages/recs/src/System.ts @@ -13,10 +13,14 @@ export function defineSystem(world: World, system: (world: World) => void): Syst /** * @param world ECS world this component is defined in * @param system Function to be called whenever any of the observable data accessed in the function changes + * @param options Optional parameters object, [requirement?] is a function that must return true or be null for system to run * @returns Function to dispose the system */ -export function defineAutorunSystem(world: World, system: () => void) { - const disposer = autorun(() => system()); +export function defineAutorunSystem(world: World, system: () => void, options?: { requirement?: () => boolean }) { + const { requirement } = options || {}; + const disposer = autorun(() => { + if (requirement == null || requirement()) system(); + }); world.registerDisposer(disposer); } @@ -24,10 +28,23 @@ export function defineAutorunSystem(world: World, system: () => void) { * @param world ECS world this component is defined in * @param observe System is rerun if any of the data accessed in this function changes. Result of this function is passed to the system. * @param system Function to be run when any of the data accessed in the observe function changes + * @param options Optional parameters object, [requirement?] is a function that must return true or be null for system to run * @returns Function to dispose the system */ -export function defineReactionSystem(world: World, observe: () => T, system: (data: T) => void) { - const disposer = reaction(observe, (data) => system(data), { fireImmediately: true }); +export function defineReactionSystem( + world: World, + observe: () => T, + system: (data: T) => void, + options?: { requirement?: () => boolean } +) { + const { requirement } = options || {}; + const disposer = reaction( + observe, + (data) => { + if (requirement == null || requirement()) system(data); + }, + { fireImmediately: true } + ); world.registerDisposer(disposer); }