Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexVipond/4fd4591deebc643b7e3bd9a5a9194599 to your computer and use it in GitHub Desktop.
Save AlexVipond/4fd4591deebc643b7e3bd9a5a9194599 to your computer and use it in GitHub Desktop.
import { reactive, effectScope, watchEffect } from 'vue'
function switchboard(value) {
let lookup = {}
let scope = effectScope()
let current
let get = () => current
let set = (newValue) => {
if (newValue === current) return
if (current !== undefined) lookup[current].state = false
current = newValue
if (lookup[newValue] === undefined) {
scope.run(() => {
lookup[newValue] = reactive({ state: true })
})
} else {
lookup[newValue].state = true
}
}
let is = (comparisonValue) => {
if (lookup[comparisonValue] === undefined) {
scope.run(() => {
lookup[comparisonValue] = reactive({ state: false })
})
return lookup[comparisonValue].state
}
return !! lookup[comparisonValue].state
}
value === undefined || set(value)
let scopedWatchEffect = (...params) => {
scope.run(() => {
watchEffect(...params)
})
}
return { get, set, is, watchEffect: scopedWatchEffect, stop: scope.stop }
}
function switchboardSet(value) {
let lookup = {}
let scope = effectScope()
let current = []
let all = () => current
let add = (newValue) => {
if (current.includes(newValue)) return
current.push(newValue)
if (lookup[newValue] === undefined) {
scope.run(() => {
lookup[newValue] = reactive({ state: true })
})
} else {
lookup[newValue].state = true
}
}
let remove = (newValue) => {
if (! current.includes(newValue)) return
current = current.filter(i => i !== newValue)
if (lookup[newValue] === undefined) {
scope.run(() => {
lookup[newValue] = reactive({ state: false })
})
} else {
lookup[newValue].state = false
}
}
let has = (comparisonValue) => {
if (lookup[comparisonValue] === undefined) {
scope.run(() => {
lookup[comparisonValue] = reactive({ state: false })
})
return false
}
return !! lookup[comparisonValue].state
}
let clear = () => {
for (let i = 0; i < current.length; i++) {
let key = current[i]
delete current[i]
lookup[key].state = false
}
current = current.filter(i => i)
}
let scopedWatchEffect = (...params) => {
scope.run(() => {
watchEffect(...params)
})
}s
value === undefined || value.forEach(i => add(i))
return { all, add, remove, has, clear, watchEffect: scopedWatchEffect, stop: scope.stop }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment