Event Delegation For Dynamic Lists

Attach one listener on the list container and resolve targets with closest so dynamically added rows work without rebinding handlers.

JavascriptData Fetching

Code

javascriptsnippet
36 lines
const list = document.querySelector('#todo-list');

// 一个监听器管所有行:新增行无需重新绑定
list.addEventListener('click', (event) => {
  const button = event.target.closest('button[data-action]');
  if (!button || !list.contains(button)) return;

  const row = button.closest('li');
  const action = button.dataset.action;

  if (action === 'remove') {
    row.remove();
  } else if (action === 'toggle') {
    row.classList.toggle('done');
    button.dataset.action = row.classList.contains('done') ? 'untoggle' : 'toggle';
  }
});

// 动态新增的行天然被上面的委托监听覆盖
function addRow(label) {
  const li = document.createElement('li');
  const text = document.createElement('span');
  text.textContent = label;
  const toggle = Object.assign(document.createElement('button'), {
    textContent: 'toggle',
    dataset: { action: 'toggle' },
  });
  const remove = Object.assign(document.createElement('button'), {
    textContent: 'remove',
    dataset: { action: 'remove' },
  });
  li.append(text, toggle, remove);
  list.appendChild(li);
}

addRow('delegated row works immediately');

Inside the snippet

Count the function addRow as the entire surface area of Event Delegation For Dynamic Lists.

Points of care

  • Uses document, so it needs a browser context — it will not run as-is in Node without shims.

Putting it to use

Entry signature: function addRow(label)

Core lines

button.dataset.action = row.classList.contains('done') ? 'untoggle' : 'toggle';

Interactive Tools for This Topic

FAQ

Does Event Delegation For Dynamic Lists run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.