示例工程 19-dom-events
19-dom-events/02-delegation/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 事件委托:从事件目标沿祖先链找匹配元素
export function findDelegatedTarget(start, selector, { matches, parentOf }) {
let current = start;
while (current) {
if (matches(current, selector)) return current;
current = parentOf(current);
}
return null;
}
export function countListeners(nodeCount, mode) {
return mode === 'delegated' ? 1 : nodeCount;
}
export function run(log = console.log) {
const nodes = {
button: { id: 'button', parent: 'li' },
li: { id: 'li', parent: 'ul' },
ul: { id: 'ul', parent: null },
};
const byId = (id) => nodes[id];
const found = findDelegatedTarget(byId('button'), 'button[data-id]', {
matches: (node, selector) => selector === 'button[data-id]' && node.id === 'button',
parentOf: (node) => (node.parent ? byId(node.parent) : null),
});
log(`从按钮向上找到:${found ? found.id : 'null'}`);
log(`1000 个节点:直接绑定 ${countListeners(1000, 'direct')} 个监听器,委托 ${countListeners(1000, 'delegated')} 个`);
log('委托把监听器挂在共同祖先上,用 closest/递归匹配判断来源。');
return { found: found ? found.id : null };
}