arnoson / kirby-vite

Use Kirby CMS together with Vite
MIT License
81 stars 7 forks source link

How to call methods? (Scope/Namespacing?) #3

Closed alancwoo closed 3 years ago

alancwoo commented 3 years ago

Hello again, sorry for another question - say I have something like src/templates/home/index.js:

import '@/index.js'
import './index.css'

const hello = () => {
    alert('Hello!')
}

and want to call the method from the php script at templates/home.php:

<span onclick="hello()">Hello</span>

What is the right way to reference this method? (it is undefined in the general scope).

arnoson commented 3 years ago

In this case you can either expose your method to the global scope explicitly

window.hello = () => alert('Hello!')

Which kind of defeats the whole purpose of using javascript modules, which is not to pollute the global scope. So I would rather register the click event in your javascript file.

<!-- templates/home.php -->
<span class="hello-button">hello<span>
// src/templates/home/index.js
const hello = () => alert('Hello!')
document.querySelector('.hello-button').addEventListener('click', hello)
alancwoo commented 3 years ago

Ok this makes sense. I'm using AlpineJS and was hoping to define functions I could use with @click etc, so have found other ways around it.

Thank you :)