Javascript object encapsulation that tracks changes


Is it possible to create an object container where changes can be tracked

Said object is a complex nested object of data. (compliant with JSON).

The wrapper allows you to get the object, and save changes, without specifically stating what the changes are

Does there exist a design pattern for this kind of encapsulation

Deep cloning is not an option since I’m trying to write a wrapper like this to avoid doing just that.

The solution of serialization should only be considered if there are no other solutions.

An example of use would be

var foo = state.get();
// change state
state.update(); // or;

A jsfiddle snippet might help :

It seems like implementing an internal hash to keep track of changes is the best option.


To clarify this is actaully done on node.js on the server. The only thing that changes is that the solution can be specific to the V8 implementation.

Problem courtesy of: Raynos


Stripping away the javascript aspect of this problem, there are only three ways to know if something has changed:

  1. Keep a copy or representation to compare with.
  2. Observe the change itself happening in-transit.
  3. Be notified of the change.

Now take these concepts back to javascript, and you have the following patterns:

  1. Copy: either a deep clone, full serialization, or a hash.
  2. Observe: force the use of a setter, or tap into the javascript engine (not very applicable)
  3. Notify: modifying the code that makes the changes to publish events (again, not very applicable).

Seeing as you’ve ruled out a deep clone and the use of setters, I think your only option is some form of serialisation… see a hash implementation here.

Solution courtesy of: David Tang

View additional discussion.