使单个MobX自动运行或对阵列中所有对象的可观察属性做出反应 [英] Make single MobX autorun or reaction for observable property of all objects in array
问题描述
我有一个@observable
类(所有示例都是Typescript/伪代码)
I have class with @observable
(all examples are Typescript/pseudocode)
class Page {
id: number = 0;
@observable
isVisible: boolean = false;
}
let array = [new Page(), new Page(), new Page()];
还有一些功能,例如:
changeVisibility(obj)
{
//ajax call like .post("/api/changeVisibility/", {id:obj.id, isVisible:obj.isVisible})
}
我想对任何对象上的isVisible
更改做出反应.
And I want to react on isVisible
change on any object.
我可以枚举数组,并做类似的事情:
I can enumerate array and make something like:
array.forEach(el => {
reaction(
() => el.isVisible,
isVis => changeVisibility(el);
});
});
但是我可以用一个功能来做到这一点吗?
一种对元素的属性变化做出反应的数组观察器".
But can I do that with one function?
Kind of "array observer that reacts to element's property change".
类似这样的东西:
reaction(array, //source
(el) => el.isVisible, //observable to react
(el) => changeVisibility(el) //callback with object
)
推荐答案
如果该响应负责发送单个页面的更新,则可以在Page
构造函数本身中设置该响应,或者在其中提供实用程序功能.页面,这样就不必使页面数组与反应处理程序数组保持同步(但作为最佳实践,如果要删除页面,请处理反应)
If the reaction is responsible for sending the the update of an individual page, I would setup that reaction in the Page
constructor itself or have a utility function in Page for that, so that you don't have to keep your pages array in sync with your reaction disposers array (but as best practice, do dispose the reaction if you want to delete the page)
这篇关于使单个MobX自动运行或对阵列中所有对象的可观察属性做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!