事件系统

Gaphor的事件系统提供了一套API,用于*处理*(handle)和*订阅*(subscribe)各类事件。

在Gaphor中,我们通过`EventManager`服务管理事件处理器(event handler)的订阅。Gaphor高度依赖事件驱动机制:

  • 模型变更通过事件触发

  • 图表变更通过事件触发

  • UI变更通过事件触发

尽管Gaphor的用户界面重度依赖GTK,但其事件分发器(event dispatcher)采用自主实现的方案。事件支持层级化结构——例如,AttributeUpdated 事件就是 ElementUpdated 事件的子类型。若需要监听元素的所有变更,只需注册`ElementUpdated`事件即可同时接收所有`AttributeUpdated`事件通知。

class gaphor.core.eventmanager.EventManager[源代码]

事件管理器(Event Manager)提供了一种灵活的事件分发机制。

事件分发是Gaphor的核心组件,它使Gaphor的各个组件能够响应应用程序中的状态变更。

事件按类型进行分发。

class subscribe(self, handler: Callable[[object], None])

注册事件处理器(handler)。

当事件通过 handle 方法触发时,相关处理器(handler)被执行。

class unsubscribe(self, handler: Callable[[object], None])

注销已注册的事件处理器。

class handle(self, *events: object)

向已注册的处理器发送事件通知。

gaphor.core.event_handler(*event_types)[源代码]

将函数/方法标记为特定类型事件的事件处理器。

对于自定义事件类型:

>>> class CustomEvent:
...     def __str__(self):
...         return type(self).__name__

您可以通过以下方式将其应用于处理器方法或函数:

>>> @event_handler(CustomEvent)
... def custom_handler(event: CustomEvent):
...     print(event)

这将允许您通过事件管理器(Event Manager)处理该事件:

>>> event_manager = EventManager()
>>> event_manager.subscribe(custom_handler)
>>> event_manager.handle(CustomEvent())
CustomEvent

Under the hood events are handled by the Generics library. For more information about how the Generic library handles events see the Generic documentation.