简体   繁体   中英

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

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
    )

如果响应负责发送单个页面的更新,则可以在Page构造函数本身中设置该响应,或者在Page中为此设置实用程序功能,这样您就不必与页面数组保持同步您的反应处置器数组(但作为最佳实践,如果要删除页面,请处置反应)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM