初次提交
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
## EventBus — 全局事件总线(Autoload: EventBus)
|
||||
## 权威接口定义:architecture_design.md §6.2
|
||||
##
|
||||
## 使用约定:
|
||||
## - 订阅:EventBus.subscribe(EventID.ENEMY_KILLED, _on_enemy_killed)
|
||||
## - 发送:EventBus.emit(EventID.ENEMY_KILLED, {"entity_id": id})
|
||||
## - 取消:EventBus.unsubscribe(EventID.ENEMY_KILLED, _on_enemy_killed)
|
||||
extends Node
|
||||
|
||||
var _listeners: Dictionary = {} # { event_id: int → Array[Callable] }
|
||||
|
||||
func subscribe(event_id: int, callback: Callable) -> void:
|
||||
if not _listeners.has(event_id):
|
||||
_listeners[event_id] = []
|
||||
var arr: Array = _listeners[event_id]
|
||||
if not arr.has(callback):
|
||||
arr.append(callback)
|
||||
|
||||
func unsubscribe(event_id: int, callback: Callable) -> void:
|
||||
if not _listeners.has(event_id):
|
||||
return
|
||||
_listeners[event_id].erase(callback)
|
||||
|
||||
func emit(event_id: int, payload: Dictionary = {}) -> void:
|
||||
if not _listeners.has(event_id):
|
||||
return
|
||||
var arr: Array = _listeners[event_id]
|
||||
# 逆序迭代防止回调内部 unsubscribe 导致跳过
|
||||
for i in range(arr.size() - 1, -1, -1):
|
||||
arr[i].call(payload)
|
||||
|
||||
## C# 批量通知接口:一次调用发送多个事件(ADR-L1 规则3)
|
||||
## events: Array of [event_id: int, payload: Dictionary]
|
||||
func emit_batch(events: Array) -> void:
|
||||
for ev in events:
|
||||
var eid: int = ev[0]
|
||||
var pay: Dictionary = ev[1] if ev.size() > 1 else {}
|
||||
emit(eid, pay)
|
||||
|
||||
## 清空所有订阅(关卡结束 / 场景切换时调用)
|
||||
func reset() -> void:
|
||||
_listeners.clear()
|
||||
Reference in New Issue
Block a user