Skip to content
Noppanit Charassinvichai edited this page Apr 4, 2014 · 4 revisions

It's often desirable to know whether or not an observable data structure has been modified since some particular point in time, typically so you can prompt the user to save their changes.

Method 1

This jsFiddle.net example shows how you can create a generic changeTracker class that, given an object graph, uses a hash function to notice changes to any part of that object graph. The change tracker will update its state automatically when any observable values change.

It also gives you a way to mark the current state as "clean", perhaps after you know the user has saved their changes. Then, the state will be regarded as "dirty" only when another change occurs.

Method 2

Ryan Niemeyer has posted a blog entry demonstrating a smart dirty flag in KnockoutJS. He provides two implementations:

  • A version that stops re-evaluating the hash function once the object graph is known to be dirty. This makes it more performant on large object graphs.
  • A version that continually re-evaluates the has function so it can detect if the object reverts back to its previous "clean" state

He also provides an example of using this to track the dirty/clean state separately for each item in an array, so you'd know which ones to send back to the server if the user clicks "save".