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

Feature/events #43

Merged
merged 5 commits into from
Jan 14, 2022
Merged

Feature/events #43

merged 5 commits into from
Jan 14, 2022

Conversation

minecrawler
Copy link
Collaborator

@smallka This is the sim-ecs events example. It works on the release/0.5.0 branch!

import {buildWorld, createSystem, ReadEvents, Storage, WriteEvents} from "../src";

/// This example creates a new event, a system that triggers the event once per second,
/// and a system that prints a message whenever the event is received.

class MyEvent {
    constructor(
        public message: string
    ) {}
}

const EventTriggerSystem = createSystem({
    myEvents: WriteEvents(MyEvent),
    lastEvent: Storage({timestamp: 0}),
}).withRunFunction(async ({myEvents, lastEvent}) => {
    if (Date.now() - lastEvent.timestamp >= 1000) {
        await myEvents.publish(new MyEvent('My event just happened!'));
        lastEvent.timestamp = Date.now();
    }
}).build();

const EventListenerSystem = createSystem({
    myEvents: ReadEvents(MyEvent),
}).withRunFunction(({myEvents}) => {
    let myEvent;
    for (myEvent of myEvents.iter()) {
        console.log(myEvent.message);
    }
}).build();


buildWorld()
    .withDefaultScheduling(root => root
        /// Stages will run after one another, however the systems inside may run in any order and even in parallel
        .addNewStage(stage => stage.addSystem(EventTriggerSystem))
        /// So, if we want to receive the shutdown event guaranteed on the same step, we need to use a later stage
        .addNewStage(stage => stage.addSystem(EventListenerSystem))
    )
    .build()
    .run()
    .catch(console.error)
    .then(() => console.log('Finished.'));

@minecrawler minecrawler added the enhancement New feature or request label Jan 14, 2022
@minecrawler minecrawler added this to the 0.5.0 milestone Jan 14, 2022
@minecrawler minecrawler merged commit e49f352 into release/0.5.0 Jan 14, 2022
@minecrawler minecrawler deleted the feature/events branch January 14, 2022 12:08
@minecrawler minecrawler mentioned this pull request Jan 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant