Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to expose and call methods from svelte component

I built a simple Banner component which is imported in _layout.html. It exposes 5 methods (dismiss, info, warning, ...).

Currently I'm using the store to keep track of these methods as in _layout.html below.

_layout.html

<main>
    <Banner ref:banner/>
    <svelte:component this={child.component} {...child.props} />
</main>

<script>
    export default {
        components: {
            Banner: '../components/Banner.html',
        },

        oncreate() {
            this.store.set({
                Banner: {
                    dismiss: this.refs.banner.dismiss,
                    danger: this.refs.banner.danger,
                    info: this.refs.banner.info,
                    success: this.refs.banner.success,
                    warning: this.refs.banner.warning
                }
            })
        }
    }

So I can call them from any part of the app like so:

blog.html

...     
  this.store.get().Banner.success('Post saved!')        
} catch (err) {
  this.store.get().Banner.danger(err)
}
...

This is working fine however I wonder if this is the best Svelte way to do it.

like image 844
Brice Avatar asked Oct 16 '22 10:10

Brice


1 Answers

Well I'm not sure of a better Svelte way. What you did looks good to me. You could

oncreate() {
    Object.assign(this, this.refs.banner);
    //or assign the exposed methods to the root component in any way
}

...
this.root.success('Post saved!');
...

Since all elements have reference to the root component.

like image 193
Ante Novokmet Avatar answered Oct 20 '22 17:10

Ante Novokmet