我正在尝试使用mobx状态管理,我想知道如何将其用于不具有内在反应性的vanilla javascript代码,并且与UI无关。
例如:在app中,应用程序加载后可能会执行多个查询,但服务器可能尚未准备好处理这些查询或其结果。为了避免竞争条件,我们对查询进行排队,然后在就绪状态发生变化时异步执行它们。
我知道如何在flux / redux中处理这个问题,因为该模型非常简单且完全与环境无关。但是在mobx中,我知道做出反应的唯一方法是使用observer
装饰器,这只在reactjs中有用。表面上看,observer
只是将我的reactjs类包装在一个aoutrun
函数中,但我无法完全理解它是如何完成的,或者我如何模仿我的行为以供我使用案件。我想要的是能够做这样的事情
class ServerState {
@observable ready = false
@action
changeReadyState(state) {
this.ready = true
}
}
const state = new ServerState()
class DataLoader {
queue = []
loadData(id) {
if(state.ready) {
Sql.query('select * from data where id = ' + id)
} else {
queue.push(id)
}
// this needs to happen as soon as the ready state changes
processEnqueuedQueries() {
for(let id of queue) {
this.loadData(id)
}
}
}
到目前为止,我提出的最好的方法是使用类似于flux的pub / sub模型,并在autorun
类的ServerState
中发布新的就绪状态。尽管如此,这并没有真正利用mobx带来的反应性。那么我如何对另一个类的可观察属性的变化作出反应呢?
答案 0 :(得分:0)
我明白了。 Mobx自动运行会观察可观察量,无论它们来自何处,都可以在函数中使用。以下是我提出的内容
class ServerState {
@observable ready = false
@action
changeReadyState(state) {
this.ready = true
}
}
const state = new ServerState()
class DataLoader {
queue = []
constructor() {
autorun(() => {
if(state.ready) {
this.processEnqueuedQueries()
}
})
}
loadData(id) {
if(state.ready) {
Sql.query('select * from data where id = ' + id)
} else {
queue.push(id)
}
// this needs to happen as soon as the ready state changes
processEnqueuedQueries() {
for(let id of queue) {
this.loadData(id)
}
}
}