Make single MobX autorun or reaction for observable property of all objects in array

冷暖自知 提交于 2019-12-12 03:48:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!