Reputation: 1609
I'm trying to build a modular app in pure vanilla JavaScript, just for the sake of it. Importing class based modules works as expected, but I'm having some trouble with exported functions, as I get function is not defined
thrown at me when I try to initialize the exported function through an onclick call.
My clickHandler.js:
export default function handleClick(target, value) {
console.log(target, value);
}
Which gets imported in my main.js:
import handleClick from '../path/to/function/clickHandler.js';
...
<button id="my-button" onclick="handleClick(this, 1)">Test button</button>
This being a very stripped-down example of what I'm working with - why would the function be undefined at that point? In my project, the buttons are located in a obj.forEach((object) => { ... }
, but I already tried to move the button with the onclick call outside of this scope, just to make sure it's not a scoping issue. Importing the function of course happens on the top of my main.js file.
Any ideas?
Upvotes: 2
Views: 1127
Reputation: 26404
Since modules have their own private scope or "namespace", inline event listeners in the markup can't access functions defined in the modules. You'll have to use addEventListener
instead:
element.addEventListener("click", (event) => handleClick(event.target, 1));
Here in the handler we're passing the event target and a value of 1
.
Upvotes: 3