-
Notifications
You must be signed in to change notification settings - Fork 0
/
on_self_change.rs
76 lines (69 loc) · 2.19 KB
/
on_self_change.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use bevy::{log::LogPlugin, prelude::*};
use bevy_inspector_egui::quick::WorldInspectorPlugin;
use bevy_ui_builder::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(LogPlugin {
level: bevy::log::Level::INFO,
filter: "wgpu=error,bevy_ui_builder=trace".to_string(),
}))
.add_plugin(WorldInspectorPlugin)
.add_plugin(UiBuilderPlugin)
.register_bind_data_source::<Counter>(true)
.add_startup_system(setup)
.add_event::<MyClickEvent>()
.add_system(handle_my_click_event)
.run();
}
#[derive(Component)]
pub struct Counter {
pub val: i32,
}
#[derive(Clone)]
pub struct MyClickEvent;
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
let mut b = UiBuilder::new(&mut commands, ());
b.set_default_text_style(TextStyle {
font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 24.,
color: Color::BLACK,
});
b.node()
.with_name("ui-root")
.with_style_modifier((StyleSize::FULL, StyleCenterChildren))
.with_component(Counter { val: 0 })
//
// this example present how to use on_change
//
.with_on_self_change(|_commands, counter: &Counter| {
//
// when Counter component change, this callback will be called
//
info!("current counter is {}", counter.val);
})
.with_children(|b| {
b.text("please see terminal output");
b.button()
.with_name("add-counter-button")
.with_style_modifier((
StyleSize::px(30., 30.),
StyleMargin::all_px(5.),
StyleCenterChildren,
))
.with_send_event_click(MyClickEvent)
.with_children(|b| {
b.text("+");
});
});
}
fn handle_my_click_event(
mut event_reader: EventReader<MyClickEvent>,
mut query: Query<&mut Counter>,
) {
for _ in event_reader.iter() {
for mut counter in query.iter_mut() {
counter.val += 1;
}
}
}