Detect when mobx observable has changed

北战南征 提交于 2020-01-03 12:33:52

问题


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

For instance, say you have this:

@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.

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?


回答1:


You could use autorun to achieve this:

@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;
});



回答2:


Create an action that will push to myObject and set myObjectChanged

@action add(item) {
    this.myObject.push(item);
    this.myObjectChanged = true;
}


来源:https://stackoverflow.com/questions/39987774/detect-when-mobx-observable-has-changed

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