The useToggleEvents composable is a versatile tool that allows developers to create event-driven functionality based on changes in a boolean value. By providing a boolean value as an argument, the composable returns functions for subscribing to events triggered when the boolean value changes to true or false. This composable abstracts away the complexity of managing event listeners and provides a clean and concise way to handle state changes and trigger corresponding actions. Whether you need to toggle UI elements, handle user interactions, or create dynamic behavior based on boolean values, the useBooleanEvent composable simplifies the process and enhances code reusability and maintainability.
Tip: Use array destructuring for semantic naming.
//Example: Let's say you're using this to toggle dark mode on your site:
const [onDarkMode, onLightMode, toggleDarkMode, isDark] =useToggleEvents()
import {useToggleEvents} from'@/composables/useToggleEvents'
const [onTrueEvent, onFalseEvent, toggle, toggleValue] =useToggleEvents()
// or pass an initialValue for the boolean being watched
// const [onTrueEvent, onFalseEvent, toggle, toggleValue] = useToggleEvents(true)
onTrueEvent(() => {
// do something every time true is toggled
})
onTrueEvent(() => {
// do something only once when true is toggled
}, {once: true})
onFalseEvent(() => {
// do something every time false is toggled
})
// toggle value
toggle()