add App::emit such that events can be emitted without acquiring a Context (#94)

This commit is contained in:
Dustin Yost
2026-07-27 23:16:59 -07:00
committed by GitHub
parent 1fe82dbcd7
commit 2542e1154a
2 changed files with 20 additions and 10 deletions
+18
View File
@@ -961,6 +961,24 @@ impl App {
self.pending_updates -= 1;
}
/// Emit an event of the specified type, which can be handled by other entities that have subscribed via `subscribe` methods on their respective contexts.
/// A globally-callable equivalent to `Context::emit` without requiring an entity update.
pub fn emit<EntityType, EventType>(&mut self, entity: &Entity<EntityType>, event: EventType)
where
EntityType: EventEmitter<EventType>,
EventType: 'static,
{
let event = self
.event_arena
.alloc(|| event)
.map(|it| it as &mut dyn Any);
self.pending_effects.push_back(Effect::Emit {
emitter: entity.entity_id(),
event_type: TypeId::of::<EventType>(),
event,
});
}
/// Arrange a callback to be invoked when the given entity calls `notify` on its respective context.
pub fn observe<W>(
&mut self,
+2 -10
View File
@@ -1,5 +1,5 @@
use crate::{
AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,
AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, EntityId, EventEmitter,
FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
};
@@ -767,15 +767,7 @@ impl<T> Context<'_, T> {
T: EventEmitter<Evt>,
Evt: 'static,
{
let event = self
.event_arena
.alloc(|| event)
.map(|it| it as &mut dyn Any);
self.app.pending_effects.push_back(Effect::Emit {
emitter: self.entity_state.entity_id,
event_type: TypeId::of::<Evt>(),
event,
});
self.app.emit(&self.entity(), event);
}
}