Skip to main content

examples/observers/
observer_custom_event.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7    pub x: f32,
8    pub y: f32,
9}
10
11#[derive(Component)]
12struct MyEvent;
13
14fn main() {
15    let world = World::new();
16
17    // Create an observer for the custom event
18    world
19        .observer::<MyEvent, &Position>()
20        .each_iter(|it, index, _pos| {
21            println!(
22                " - {}: {}: {}",
23                it.event().name(),
24                it.event_id().to_str(),
25                it.entity(index)
26            );
27        });
28
29    // The observer query can be matched against the entity, so make sure it
30    // has the Position component before emitting the event. This does not
31    // trigger the observer yet.
32    let entity = world.entity_named("e1").set(Position { x: 10.0, y: 20.0 });
33
34    // Emit the custom event. This triggers the observer.
35    world
36        .event()
37        .add(Position::id())
38        .entity(entity)
39        .emit(&MyEvent);
40
41    // Output:
42    //  - MyEvent: Position: e1
43}
44
45#[cfg(feature = "flecs_nightly_tests")]
46#[test]
47fn test() {
48    let output_capture = OutputCapture::capture().unwrap();
49    main();
50    output_capture.test("observer_custom_event".to_string());
51}