检测可观察的Mobx何时更改 [英] Detect when mobx observable has changed

查看:102
本文介绍了检测可观察的Mobx何时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以任何方式检测到可观察到的变化?

Is it possible to detect when an observable changes in any way?

例如,说你有这个:

@observable myObject = [{id: 1, name: 'apples'}, {id: 2, name: 'banana' }]

然后,在一些用户输入下,值会更改.我如何轻松检测到这一点?

And later on, with some user input, the values change. How can I detect this easily?

我想添加一个全局的保存"按钮,但是只有在自初始加载以来该可观察项已更改的情况下,才使其可单击.

I want to add a global "save" button, but only make it clickable if that observable has changed since the initial load.

我当前的解决方案是添加另一个返回true/false的可观察的myObjectChanged,并且无论组件在myObject中更改数据的位置如何,我还添加一行将myObjectChanged更改为true的行.而且,如果单击保存按钮,它将保存并将可观察到的值更改回false.

My current solution is to add another observable myObjectChanged that returns true/false, and wherever a component changes the data in the myObject, I also add a line that changes the myObjectChanged to true. And if the save button is clicked, it saves and changes that observable back to false.

这导致大量额外的代码行散布在整个代码中.有更好/更清洁的方法吗?

This results in lots of extra lines of code sprinkled throughout. Is there a better/cleaner way to do it?

推荐答案

您可以使用autorun来实现:

@observable myObject = [{id: 1, name: 'apples'}, {id: 2, name: 'banana' }]
@observable state = { dirty: false }

let firstAutorun = true;
autorun(() => {
  // `JSON.stringify` will touch all properties of `myObject` so
  // they are automatically observed.
  const json = JSON.stringify(myObject);
  if (!firstAutorun) {
    state.dirty = true;
  }
  firstAutorun = false;
});

这篇关于检测可观察的Mobx何时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆