如何生成适用于整个纯类属性的细粒度信号



我有一个类,它保存输入事件并允许我查询状态。

class Input {
btn() { return this._btn }
_release() { this._btn = -1 }
_press() { this._btn = 0 }
listen() {
document.addEventListener('keydown', e => this._press())
document.addEventListener('keyup', e => this._release())
}
update() {
if (this._btn >= 0) this._btn++
}
}

我这样使用这个类:

let input = new Input()
input.listen()
function update_every_frame() {
input.update()
}
function check_for_input() {
if (input.btn() > 0) {
console.log('here')
}
}

因此,使用实体式编码,我想发出一个信号,每当按下输入btn时就会发生变化:

let [input, setInput] = createSignal(new Input(), { equals: false })
function update_every_frame() {
setInput(input => { input.update(); return input })
}

const check_for_input = () => { return input().btn() }

现在check_for_input是一个反应属性,它返回按钮按下。除了这处房产日期每帧,因为我每帧调用input.update

我不希望在数据级别使用细粒度的信号,因为我用信号污染了纯数据类。是因为我想创建一个独立于库的数据类并对其进行测试。

那么,我该如何生成适用于整个纯类属性的细粒度信号呢。

编辑

例如,我如何为数组或类上的getter属性创建信号或备忘录,以便在类更新其属性时相应地更新信号:

class Test {
array: Array
a: number = 0
get computed(): {
return this.a < 4 ? 1 : 0
}
update() {
this.a = 10
}
}
let [instance, setInstance] = createSignal(new Test(), { equals: false })
let arraySignal = createMemo(() => instance().array)
let computedSignal = createMemo(() =>
instance.computed)

computedSignal如何更新此方法调用:

setInstance(instance => instance.update())

可以这样做的一种方法是:

import {createMutable} from 'solid-js/store'
import {createEffect} from 'solid-js'
class Foo {
// any properties here
whatever = 123
constructor() {
return createMutable(this)
}
}
const f = new Foo
createEffect(() => console.log(f.whatever))
f.whatever++ // reactive

或者保持课堂的纯粹性:

import {createMutable} from 'solid-js/store'
import {createEffect} from 'solid-js'
class Foo {
// any properties here
whatever = 123
}
const f = createMutable(new Foo)
createEffect(() => console.log(f.whatever))
f.whatever++ // reactive

你说过你不想为每个属性生成信号,但使用classy-solid,你可以用一种仍然感觉像编写一个常规类的方式来实现:

import {reactive, signal} from 'classy-solid'
@reactive
class Foo {
@signal whatever = 123
}
const f = new Foo
createEffect(() => console.log(f.whatever))
f.whatever++ // reactive

最新更新