[英]Using mobx for non-ui state management
我正在尝试使用mobx状态管理,并且想知道如何将其用于固有的非反应性且与UI无关的原始javascript代码。
例如:在应用程序中,加载应用程序后可能会立即执行几个查询,但是服务器可能尚未准备好处理这些查询或其结果。 为了避免争用条件,我们将查询排队,然后在就绪状态更改后异步执行它们。
我知道我将如何在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模型,并在ServerState
类的autorun
发布新的就绪状态。 但是,这并没有真正利用mobx带来的反应性。 那么,我如何对一个类的可观察属性的变化做出反应呢?
我想到了。 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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.