Svelte: Capture events through {{yield}} or <slot>

Created on 16 Jan 2018  路  3Comments  路  Source: sveltejs/svelte

It seems events do not go through a {{yield}} or <slot> boundary. Test case here: https://svelte.technology/repl?version=1.51.1&gist=535261a820567f4c9bd39b9e2bbccb51

This is a bit limiting in terms of designing composable elements, for example:

<Tabs>
  <Tab link="#a" label="Content" />
  <Tab link="#b" label="Extras" />
</Tabs>

Tabs here needs a slot for the inner components, but then they are unable to communicate with the parent to set the _selected tab_. Is there another obvious solution?

question rfc-1

All 3 comments

AFAIK
First of all {{yield}} is deprecated and is replaced by <slot>.

Secondly, items inside slots are not in the context of the component containing the slot.
Instead they are in the context of the component that contains the slot parent (App.html in this case).

Therefore you have to forward the event on (cos no event bubbling in svelte), or call a method on App.html

Try clicking the slotted button here:
https://svelte.technology/repl?version=1.51.1&gist=0e8afecc1ea769458c57413dd0d6ea43

@ekhaled thanks for chiming in.

For the example I mentioned, this would mean the consumer of the component would have to do the forwarding, and also ensure that the value fired matches the one used for the selected state:

<Tabs>
  <Tab on:click="fire('click', '#a')" link="#a" ... />
  <Tab on:click="fire('click', '#b')" link="#b"... />
</Tabs>

Not a very nice API. Since the output of

<Tabs>
    <slot><Tab /></slot>
</Tabs>

and

<Tabs>
    <Tab />
</Tabs>

Is exactly the same, it seems a fair assumption that their behaviour re. events should be the same. The slot there becomes an 'invisible boundary'.

It's not automatic event bubbling (which isn't something we want to do), but v3 now has the new component composition context API, which allows for more powerful interaction between parent and child components. A lot of situations in v2 that required component events can also now be replaced by passing callbacks as props. Closing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

clitetailor picture clitetailor  路  3Comments

angelozehr picture angelozehr  路  3Comments

robnagler picture robnagler  路  3Comments

thoughtspile picture thoughtspile  路  3Comments

Rich-Harris picture Rich-Harris  路  3Comments