Checkout the article on how I built this composable here.

Description

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.

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

Arguments

KeyTypeDefaultDescription
initialValuebooleanfalseThe initial value of the boolean value to watch.

Returns

KeyTypeDescription
onTrueEventfunctionPass a callback and an options object to execute when a true event is fired.
onFalseEventfunctionPass a callback and an options object to execute when a false event is fired.
togglefunctiontoggle the boolean value between true/false values.
toggleValueref<boolean>the current value of the boolean being watched.

Options

KeyTypeDescription
oncebooleanflag to determine if callback should only be notified once or not.