javascript - How to implement side effect on observable property?
问题描述
I relativly new in Mobx and I need automaticaly call a function when this observable array is update. The observable array :
@observable Todos = []
I've many function to manage this array (addToso, removeTodo, ...) and I would like to avoid having to call this function in each of the functions that update this array.
For exemple :
@action addTodo(todo, important) {
const newTodo = {
id : Math.random(),
text : todo,
isImportant : important,
completed : false,
date : Date.now()
}
this.Todos.push(newTodo)
}
I want when Todos
is update a function automaticaly run for save Todos
in my database.
const UpdateDbData = (id, newTodos) => {
firebase.database().ref(`users/${id}`).update({
todos : newTodos
})
.catch(error => console.log(error))
}
Here newTodo
is for the current value of the Todos
array (id for the user id)
I've test with autorun
and reaction
but I dont understand how use them properly.
How can do that ?
解决方案
我更喜欢这种mobx.observe
方法:https ://mobx.js.org/refguide/observe.html#observe 。
你可以使用它:
constructor(){
mobx.observe(this.Todos, (change) => {
// update your backend data here.
doSomething(this.Todos);
})
}
此方法仅在 todos 数组更改时触发。不在任何其他正在更改的属性上。
笔记:
- 您可以提取该方法,以便您可以轻松地使其在不同的属性上执行(只需在其他属性上使用 mobx.observe)
- 如果有很多更改,您可以将方法包装在 debounce 方法中
- 如果你观察到两次方法会被触发两次,所以去抖动很方便!
- 每个(事务)操作只调用一次观察方法。(就像自动运行一样)。
推荐阅读
- python - 我不知道 tkinter 的 after 方法是如何工作的
- css - 不透明度:0 + 指针事件:无 vs 显示:无
- cordova - 使用 Cordova In app Browser 从视频播放器下载文件
- reactjs - 标签
在此浏览器中无法识别。如果您打算渲染一个 React 组件,请以大写字母开头 - java - 如何覆盖这段代码的 100% 分支?
- python - 我们可以使用 VODE 使用 scipy.integrate.ode 修改集成步骤之间的解向量吗?
- python - 使用python的Qgis插件构建器
- linux - linux不能用分号设置环境变量
- python - Python - 如果列名包含特定字符串,则更改该列中的值,否则值保持不变
- excel - 进一步划分已经很复杂的计算