信号,基于推-拉的算法

We have been using Signals in production for years via several modern front-end frameworks like Solid, Vue, and others, but few of us are able to explain how they work internally. I wanted to dig into it, especially diving deep into the push-pull based algorithm, the core mechanism behind their reactivity. The subject is fascinating.

多年来,我们通过 Solid、Vue 等现代前端框架在生产环境中使用 Signals,但我们中很少有人能解释其内部工作原理。我想深入研究一下,特别是深入探讨基于 push-pull 的算法,这是其 reactivity 背后的核心机制。这个主题非常迷人。

The state of the world

世界的状态

Imagine an application as a world where we describe the set of rules that govern it. Once a rule is defined, our program will no longer be able to change it.

将一个应用程序想象成一个世界,我们在其中描述支配它的规则集。一旦规则被定义,我们的程序将无法再更改它。

For example, we decide that in our world, any y value must be equal to 2 * x. We define this rule, and from then on, whenever x changes, y will automatically adjust. We can define as many rules as we want. They can even depend on each other by deciding that z must be equal to y + 1, and so on.

例如,我们决定在我们的世界中,任何 y 值必须等于 2 * x。我们定义了这个规则,从那时起,无论何时 x 发生变化,y 都会自动调整。我们可以定义任意数量的规则。它们甚至可以相互依赖,比如决定 z 必须等于 y + 1,依此类推。

Now we press the play button, our program starts, the world is running, and the rules we have defined are now in effect over time. (think of it as our runtime).

现在我们按下播放按钮,程序启动,世界开始运行,我们定义的规则现在随着时间的推移生效。(可以把它看作是我们的 runtime)。

x

x

7

7

y = x * 2

y = x * 2

14

14

z = y + 1

z = y + 1

15

15

And then, we just have to observe. We can modify x and see how y and z automatically adjust to comply with the rules we have established. It's like a spreadsheet where dependent cells automatically update when their sources change. In other words, derived values are reactive to changes in their dependencies.

然后,我们只需要观察。我们可以修改 x,看看 yz 如何自动调整以符合我们建立的规则。这就像电子表格,当源数据改变时,依赖的单元格会自动更新。换句话说,派生值对其依赖项的变化是响应式的。

These derived values behave like pure functions: no side effects, no mutable state. In the next example, time is a source that changes continuously while rotation is derived from it. The square simply reflects the result of this transformation that i...

开通本站会员,查看完整译文。

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-06-26 17:25
浙ICP备14020137号-1 $mapa de visitantes$