atomiks / tippyjs

Tooltip, popover, dropdown, and menu library
https://atomiks.github.io/tippyjs/
MIT License
11.92k stars 520 forks source link

Set different props in event delegation #912

Closed pd4d10 closed 3 years ago

pd4d10 commented 3 years ago

It's good to have event delegation addon, but there seems no way to set different props in different instances.

How about adding a function prop to do this?

delegate('#parent', {
  target: '.child',
  setInstanceProps(target) {
    // Set different props by the target
  }
});
atomiks commented 3 years ago

You can use set props as data attributes

pd4d10 commented 3 years ago

Thanks for the quick reply.

Do you mean data attributes like data-tippy-content? It does work, but only for primitive values. For example:

tippy(targets, {
  // string
  content: 'Hello',
  // Element
  content: document.createElement('div'),
  // (reference) => string | Element
  content: (reference) => reference.getAttribute('title'),
});

The second and third are not primitive values and do not work in this case.

atomiks commented 3 years ago

This can be added as a feature I suppose, so it would allow you to set the props based on the target that was passed in:

delegate('#parent', {
  target: '.child',
  getTargetProps(target) {
    // random content for <div class="random" />
    return target.className === 'random'
      ? {content: () => Math.random()}
      : {};
  }
});
pd4d10 commented 3 years ago

Any updates? I've implemented your proposal here, which works fine currently. Perhaps I can send a pull request if needed.

atomiks commented 3 years ago

Sorry, I just realized you can use onCreate() to achieve the same thing.

delegate('#parent', {
  target: '.child',
  onCreate({reference, setProps}) {
    // random content for <div class="random" />
    setProps({
      content: reference.className === 'random'
        ? Math.random()
        : 'default'
    });
  }
});