Skip to content

Instantly share code, notes, and snippets.

@beyond-code-github
Last active January 3, 2016 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beyond-code-github/8385597 to your computer and use it in GitHub Desktop.
Save beyond-code-github/8385597 to your computer and use it in GitHub Desktop.
Modified track changes knockout extended that can handle detection of changes to complex objects
var traverseObservables = function (obj, action) {
ko.utils.arrayForEach(getObjProperties(obj), function (observable) {
if (observable && observable.value && !observable.value.nodeType && ko.isObservable(observable.value)) {
action(observable);
}
});
};
ko.extenders.trackChange = function (target, track) {
if (track) {
target.hasValueChanged = ko.observable(false);
target.hasDirtyProperties = ko.observable(false);
target.isDirty = ko.computed(function () {
return target.hasValueChanged() || target.hasDirtyProperties();
});
var unwrapped = target();
if ((typeof unwrapped == "object") && (unwrapped !== null)) {
traverseObservables(unwrapped, function (obj) {
applyChangeTrackingToObservable(obj.value);
obj.value.isDirty.subscribe(function (isdirty) {
if (isdirty) target.hasDirtyProperties(true);
});
});
}
target.originalValue = target();
target.subscribe(function (newValue) {
// use != not !== so numbers will equate naturally
target.hasValueChanged(newValue != target.originalValue);
target.hasValueChanged.valueHasMutated();
});
}
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment