NAG
NAG

Reputation: 501

How to access $dispatch and other magic properties of Alpinejs from vanilla js file?

I'm trying to build a toast notification component in Alpine.js. But I'm not getting to send notification from vanilla js files.

<div
    x-data="
        {
            notices: [],
            visible: [],
            add(notice) {
                notice.id = Date.now()
                this.notices.push(notice)
                this.fire(notice.id)
            },
            fire(id) {
                this.visible.push(this.notices.find(notice => notice.id == id))
                const timeShown = 10000 * this.visible.length
                setTimeout(() => {
                    this.remove(id)
                }, timeShown)
            },
            remove(id) {
                const notice = this.visible.find(notice => notice.id == id)
                const index = this.visible.indexOf(notice)
                this.visible.splice(index, 1)
            },
        }
    "
    class="z-50 p-7 fixed inset-0 w-screen flex flex-col-reverse items-end justify-end pointer-events-none"
    @notice.window="add($event.detail)">
    <template x-for="notice of notices" :key="notice.id">
        <div
            x-show="visible.includes(notice)"
            x-transition:enter="transition ease-in duration-400"
            x-transition:enter-start="transform opacity-0 translate-x-full"
            x-transition:enter-end="transform opacity-100"
            x-transition:leave="transition ease-out duration-500"
            x-transition:leave-start="transform translate-x-0 opacity-100"
            x-transition:leave-end="transform translate-x-full opacity-0"§
            @click="remove(notice.id)"
            class="rounded mb-4 p-3 w-full max-w-md text-green-800 shadow-lg cursor-pointer pointer-events-auto bg-green-200"
            x-text="notice.text">
        </div>
    </template>
</div>

https://codepen.io/nuno360/pen/WNGKmeL

From vanilla js file how I can send notices to this component?

Upvotes: 4

Views: 5110

Answers (1)

Hugo
Hugo

Reputation: 3888

You can create a custom event and dispatch it (assuming you're selecting an element of some sort) with element.dispatchEvent(new CustomEvent('notice', { detail: {}, bubbles: true }))

Upvotes: 4

Related Questions