gullerya / object-observer

Object Observer functionality of JavaScript objects/arrays via native Proxy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Any way to prevent changes?

NoxLP opened this issue · comments

While using the observer I've seen that even if I throw an error in the observe callback, the changes still happen.

I need to prevent the changes to happen if certain conditions are wrong. Is there any way to achieve this?

Hi,

The answer is no, there is no way to 'rollback' the change from within the observer and the fact that throwing error within the callback is not failing to update is by design - there are even tests dedicated to ensure that callback's error not only won't rollback the change but not even prevent other callbacks from being called.

I think that it would be wrong to implement such a functionality:

  • by it's very definition observer is not a mutative entity, but only observing
  • the way the implementation works is that the change has already happened at the callback/s phase, so we can't talk about 'prevent'
  • callbacks order is not promised, so even if hypothetically some callback would prevent the change, others has already been run assuming the change happened - we'll be getting into total mess

The only thing I can suggest is to actually do a new change back to the prev value (you do have the new and the old values on the change object, as well as the essence of change) - think of kind of a rollback from within your own callback.
This way you'll trigger a new change, which will be running a new callback/s invokation. Unless you are using and async flavor, this one will even be running only after all the callback/s of the current change done, so pretty much logically right.

It makes sense, I'll try your "rollback" suggestion.

Thanks for take your time and clarify it.