Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass added element in ea.collection.item-added event #6347

Open
wants to merge 1 commit into
base: 4.x
Choose a base branch
from

Conversation

zorn-v
Copy link
Contributor

@zorn-v zorn-v commented Jul 1, 2024

Sometimes (in my case "always") need to get new inserted element in collection.
For example to attach events to sub form elements etc.

https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent

Currently I use someting like this, which looks not so good

document.addEventListener('ea.collection.item-added', () => {
  const someSelectorInThatCollection = 'select[name*="[inventory]"]'
  const processedCssClass = 'some-class-processed'
  document.querySelectorAll(`${someSelectorInThatCollection}:not(.${processedCssClass})`).forEach((el) => {
    el.classList.add(processedCssClass)
    // do my job here like
    el.addEventListener('change', function () {
      this.parentNode.querySelector('.some-btn').disabled = !this.value
    })
  })
})

With proposed changes it can be refactored to

document.addEventListener('ea.collection.item-added', (e) => {
  const someSelectorInThatCollection = 'select[name*="[inventory]"]'
  const el = e.detail.newElement.querySelector(someSelectorInThatCollection)
  // maybe check like if not el then return
  el.addEventListener('change', function () {
    this.parentNode.querySelector('.some-btn').disabled = !this.value
  })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant