示例工程 19-dom-events
19-dom-events/01-event-flow/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 事件流三阶段的模型:捕获 → 目标 → 冒泡
export function simulateDispatch(path) {
if (!Array.isArray(path) || path.length === 0) return [];
const target = path[path.length - 1];
const ancestors = path.slice(0, -1);
const order = [];
for (const node of ancestors) order.push(`capture:${node}`);
order.push(`target:${target}`);
for (const node of [...ancestors].reverse()) order.push(`bubble:${node}`);
return order;
}
export function run(log = console.log) {
const order = simulateDispatch(['outer', 'inner', 'button']);
log(`顺序:${order.join(' → ')}`);
log('捕获从外到内,目标阶段执行目标上的监听器,冒泡从内到外。');
log('addEventListener 第三参数 true 表示捕获阶段,默认 false 表示冒泡。');
return order;
}