Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65646654/how-to-access-dispatch-and-other-magic-properties-of-alpinejs-from-vanilla-js-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...