feat(framework): core EventBus(类型化+故障隔离)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-28 14:21:26 +08:00
co-authored by Claude Opus 4.8
parent 56dbfeb5e2
commit bfd9339f64
2 changed files with 69 additions and 0 deletions
@@ -0,0 +1,40 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventBus } from '../../YouleNexus/assets/framework/core/events.ts';
test('on/emit 传递参数', () => {
const bus = new EventBus<{ hi: [number, string] }>();
let got: [number, string] | null = null;
bus.on('hi', (n, s) => { got = [n, s]; });
bus.emit('hi', 7, 'x');
assert.deepEqual(got, [7, 'x']);
});
test('off 取消订阅', () => {
const bus = new EventBus<{ ping: [] }>();
let count = 0;
const fn = () => { count++; };
bus.on('ping', fn);
bus.emit('ping');
bus.off('ping', fn);
bus.emit('ping');
assert.equal(count, 1);
});
test('once 只触发一次', () => {
const bus = new EventBus<{ ping: [] }>();
let count = 0;
bus.once('ping', () => { count++; });
bus.emit('ping');
bus.emit('ping');
assert.equal(count, 1);
});
test('一个事件订阅者抛错不影响其它订阅者', () => {
const bus = new EventBus<{ ping: [] }>();
let reached = false;
bus.on('ping', () => { throw new Error('boom'); });
bus.on('ping', () => { reached = true; });
bus.emit('ping');
assert.equal(reached, true);
});