问题
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()];
And some functions like:
changeVisibility(obj)
{
//ajax call like .post("/api/changeVisibility/", {id:obj.id, isVisible:obj.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".
Something like this:
reaction(array, //source
(el) => el.isVisible, //observable to react
(el) => changeVisibility(el) //callback with object
)
回答1:
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)
来源:https://stackoverflow.com/questions/40568576/make-single-mobx-autorun-or-reaction-for-observable-property-of-all-objects-in-a