2

I have a user object, and I want to track changes in case the user edits their information, however they can say 'discard changes' and it returns to the previous state of the user object on load.

My solution was to deepClone the original object into a backup var, to give it it's own reference points, then compare the user object to the backup object --- again using lodash

I watch the object using angular #$watch, and if !_.isEqual(user, backup).

$scope.$on '$routeChangeStart', (e, next) -> if !_.isEqual(user, backup) console.log 'changes made'

However this returns false, even when there are no changes? It's as if the two objects are not equal any longer, even though all the keys and values are identical? I assume more happens than what I see when I deepClone.

Any better approaches? And what am I doing wrong?

2 Answers2

0

The problem is most likely that user has been altered by angular. Angular adds some properties for tracking to objects bound to the view (these properties start with $ or $$). If your objects don't have such 'native' properties, you could try to do a deepOmit on user first.

Community
  • 1
  • 1
CaringDev
  • 8,391
  • 1
  • 24
  • 43
0

This is a classic example when the concept of immutability would help a lot. If your object would be immutable a copy of it would only mean a pointer to the original object and comparisons are thereby more robust in my opinion. Check out https://facebook.github.io/immutable-js/ if you would like to know why facebook has embraced it (and maybe try using it yourself).

vikeri
  • 642
  • 6
  • 16
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/10575950) – Benjamin Dec 16 '15 at 00:43
  • @Benjamin I know it does not address the question straight on, but it focuses on *Any better approaches?*. – vikeri Dec 26 '15 at 21:54