Skip to main content

examples/observers/
observer_entity_event.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4// Entity events are events that are emitted and observed for a specific entity.
5// They are a thin wrapper around regular observers, which match against queries
6// instead of single entities. While they work similarly under the hood, entity
7// events provide a much simpler API.
8//
9// An entity event only needs two pieces of data:
10// - The entity on which to emit the event
11// - The event to emit
12
13// An event without payload
14#[derive(Component)]
15struct Click;
16
17// An event with payload
18#[derive(Component)]
19struct Resize {
20    width: f32,
21    height: f32,
22}
23
24#[derive(Debug, Copy, Clone)]
25enum CloseReason {
26    User,
27    _System,
28}
29
30#[derive(Component)]
31struct CloseRequested {
32    reason: CloseReason,
33}
34
35fn main() {
36    let world = World::new();
37
38    // Create an observer for the CloseRequested event to listen to any entity.
39    world
40        .observer::<CloseRequested, ()>()
41        .with(id::<flecs::Any>())
42        .each_iter(|it, _index, _| {
43            let reason = it.param().reason;
44            println!("Close request with reason: {reason:?}");
45        });
46
47    let widget = world.entity_named("MyWidget");
48    println!("widget: {widget:?}");
49
50    // Observe the Click event on the widget entity.
51    widget.observe::<Click>(|| {
52        println!("clicked!");
53    });
54
55    widget.observe_entity::<Click>(|entity| {
56        println!("clicked on {:?}", entity.name());
57    });
58
59    // Observe the Resize event on the widget entity.
60    widget.observe_payload(|payload: &Resize| {
61        println!(
62            "widget resized to {{ {}, {} }}!",
63            payload.width, payload.height
64        );
65    });
66
67    widget.observe_payload_entity(|entity, payload: &Resize| {
68        println!(
69            "{} resized to {{ {}, {} }}!",
70            entity.name(),
71            payload.width,
72            payload.height
73        );
74    });
75
76    widget.emit(&Click);
77
78    widget.emit(&Resize {
79        width: 100.0,
80        height: 200.0,
81    });
82
83    widget.emit(&CloseRequested {
84        reason: CloseReason::User,
85    });
86
87    // Output:
88    //  widget: Entity name: MyWidget -- id: 506 -- archetype: (Identifier,Name)
89    //  clicked on "MyWidget"
90    //  clicked!
91    //  MyWidget resized to { 100, 200 }!
92    //  widget resized to { 100, 200 }!
93    //  Close request with reason: User
94}
95
96#[cfg(feature = "flecs_nightly_tests")]
97#[test]
98fn test() {
99    let output_capture = OutputCapture::capture().unwrap();
100    main();
101    output_capture.test("observer_entity_event".to_string());
102}