To handle user interactions, DOM event listeners can be added via the events
object on your component. Joystick automatically uses the native .addEventListener()
method to register listeners, scoped to the current component's DOM.
Joystick also handles cleanup of listeners between renders, ensuring duplicate listeners aren't attached.
Example Usage
ui/pages/index/index.js
import joystick from '@joystick.js/ui';
const Index = joystick.component({
events: {
'click button': (event = {}, instance = {}) => {
window.alert('DOM event detected!');
},
},
render: () => {
return `
<div>
<button>Click Me</button>
</div>
`;
},
});
export default Index;
In the example above, we attach a click
event to a button
element by defining a key/value pair in the events
object. The key is a string combining the event type and a CSS selector (e.g. 'click button'
), and the value is a function that will be called when the event is triggered.
The function receives two arguments:
- The native
event
object (unmodified from.addEventListener()
). - The current
component_instance
.
Any valid selector you’d pass to document.querySelector()
can be used in the key.
API
Definition
events: {
'<event_name> <selector>': (event: DOMEvent, component_instance: object) => void;
}
Parameters
- <event_name> <selector> function
-
A key/value pair where the key is a string of the form '<event_name> <selector>' and the value is a function to run when the event is triggered on the matched element.
- event DOMEvent required
- The native DOM event triggered on the element.
- component_instance object required
- The current component instance where the event occurred.