Skip to content

Commit

Permalink
feat(recs): add optional parameters to reaction and autorun systems
Browse files Browse the repository at this point in the history
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
  • Loading branch information
davidkol authored and alvrs committed Jun 9, 2022
1 parent a06a9c5 commit 451209f
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions packages/recs/src/System.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,38 @@ 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);
}

/**
* @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<T>(world: World, observe: () => T, system: (data: T) => void) {
const disposer = reaction(observe, (data) => system(data), { fireImmediately: true });
export function defineReactionSystem<T>(
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);
}

Expand Down

0 comments on commit 451209f

Please sign in to comment.