创建自定义可观察对象 {🚀}
在某些情况下,您可能希望拥有更多数据结构或其他事物(例如流),这些事物可以在反应性计算中使用。通过使用 **原子** 来实现这一点,原子是 MobX 在内部用于所有可观察数据类型的类。原子可以用来向 MobX 信号某个可观察数据源已被观察或更改,并且 MobX 将让原子知道它何时被使用以及何时不被使用。
**提示**:在许多情况下,您可以通过创建一个普通可观察对象并使用
onBecomeObserved
实用程序来避免创建您自己的原子的需要,以便在 MobX 开始跟踪它时收到通知。
以下示例演示了如何创建一个返回当前日期时间且可观察的 Clock
,它可以在反应性函数中使用。此时钟实际上只有在有人观察它时才会滴答。
此示例演示了 Atom
类的完整 API。有关更多信息,请参阅 createAtom
。
import { createAtom, autorun } from "mobx"
class Clock {
atom
intervalHandler = null
currentDateTime
constructor() {
// Creates an atom to interact with the MobX core algorithm.
this.atom = createAtom(
// 1st parameter:
// - Atom's name, for debugging purposes.
"Clock",
// 2nd (optional) parameter:
// - Callback for when this atom transitions from unobserved to observed.
() => this.startTicking(),
// 3rd (optional) parameter:
// - Callback for when this atom transitions from observed to unobserved.
() => this.stopTicking()
// The same atom transitions between these two states multiple times.
)
}
getTime() {
// Let MobX know this observable data source has been used.
//
// reportObserved will return true if the atom is currently being observed
// by some reaction. If needed, it will also trigger the startTicking
// onBecomeObserved event handler.
if (this.atom.reportObserved()) {
return this.currentDateTime
} else {
// getTime was called, but not while a reaction was running, hence
// nobody depends on this value, and the startTicking onBecomeObserved
// handler won't be fired.
//
// Depending on the nature of your atom it might behave differently
// in such circumstances, like throwing an error, returning a default
// value, etc.
return new Date()
}
}
tick() {
this.currentDateTime = new Date()
this.atom.reportChanged() // Let MobX know that this data source has changed.
}
startTicking() {
this.tick() // Initial tick.
this.intervalHandler = setInterval(() => this.tick(), 1000)
}
stopTicking() {
clearInterval(this.intervalHandler)
this.intervalHandler = null
}
}
const clock = new Clock()
const disposer = autorun(() => console.log(clock.getTime()))
// Prints the time every second.
// Stop printing. If nobody else uses the same `clock`, it will stop ticking as well.
disposer()