ctx.subscribe() 监听引擎状态变化。事件回调不接收参数;需要数据时,通过对应的 ctx API读取最新状态。
API
| 方法 | 返回值 | 说明 |
|---|
subscribe(event, handler) | 取消订阅函数 | 事件发生时调用无参数的 handler |
可用事件
| 事件 | 触发时机 | 在 handler 中读取数据 |
|---|
dialogue:changed | 对话内容或可见性变化 | ctx.dialogue.line() |
choice:opened | 选项面板打开 | ctx.dialogue.choice() |
choice:closed | 选项面板关闭 | ctx.dialogue.choice() |
variable:changed | 任意运行时变量变化 | ctx.variables.get(name) |
archive:changed | 存档、读档或删除后 | await ctx.archive.list() |
history:changed | 历史记录更新 | ctx.history.entries() |
config:changed | 引擎配置变化 | ctx.config.get(key) |
fragment:entered | 进入 Fragment | 无附加负载 |
fragment:exited | 离开 Fragment | 无附加负载 |
案例:好感度达到 100 时打开提示
输入: 变量 affection 当前为 95,之后由剧本或扩展写入 100。
const unsubscribe = ctx.subscribe("variable:changed", () => {
const affection = ctx.variables.get<number>("affection");
if (affection === 100) {
void ctx.ui.show("affection-max-toast");
}
});
ctx.variables.set("affection", 100);
输出: variable:changed 触发后,回调读取到 100,affection-max-toast 被打开。subscribe() 的直接输出是 unsubscribe 函数;调用它后,后续变量变化不再触发该回调。
React 中清理订阅
useEffect(() => {
return ctx.subscribe("dialogue:changed", () => {
console.log(ctx.dialogue.line());
});
}, [ctx]);
React 组件中把取消订阅函数作为 useEffect 的清理函数返回,可以避免组件卸载后继续执行回调。