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 触发后,回调读取到 100affection-max-toast 被打开。subscribe() 的直接输出是 unsubscribe 函数;调用它后,后续变量变化不再触发该回调。

React 中清理订阅

useEffect(() => {
  return ctx.subscribe("dialogue:changed", () => {
    console.log(ctx.dialogue.line());
  });
}, [ctx]);
React 组件中把取消订阅函数作为 useEffect 的清理函数返回,可以避免组件卸载后继续执行回调。