ralix icon indicating copy to clipboard operation
ralix copied to clipboard

Adding a new helper to create a wrapper for `MutationObserver`

Open franpb14 opened this issue 1 year ago • 1 comments

Let's imagine we have a list of menus that we want to observe and do something if that menu is opened, right now we should something like this:

findAll('.menu').forEach(menu => {
  const observerMenu = new MutationObserver(() => {
    if (hasClass(menu, 'opened')) ...
  })
  observerMenu.observe(menu, { attributes: true })
})

so my suggestion is to create a wrapper the helper would be something like:

observer(query, callback, options = { attributes: true }) {
  findAll(query).forEach(element => {
    const observerMenu = new MutationObserver((mutationList, observer) => {
      callback(element, mutationList)
    })
    observerMenu.observe(element, options)
  })
}

so we can just write

observer('.menu', currentTarget => { if (hasClass(currentTarget, 'opened')) ...})

other option for the helper could be:

observer(query, callback, options = { attributes: true }) {
    const observerMenu = new MutationObserver((mutationList, observer) => {
      callback(mutationList)
    })
    findAll(query).forEach(element => { observerMenu.observe(element, options) })
  })
}

In this case we are not creating a MutationObserver for each element but we don't have the currentTarget so we should use finds or something inside the callback

franpb14 avatar Mar 06 '24 11:03 franpb14

@franpb14 I have very little experience with MutationObserver API, so at this point it's hard for me to decide between both proposals or even if that's enough of common complexity to justify a new helper.

@jfelip937 @araluce @lautarocastillo Could you please guys give your feedback (if any)?

markets avatar May 07 '24 17:05 markets