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/8385560 to your computer and use it in GitHub Desktop.
Save beyond-code-github/8385560 to your computer and use it in GitHub Desktop.
Change tracking for flat viewmodels, all properties must be observables
var getObjProperties = function (obj) {
var objProperties = [];
var val = ko.utils.unwrapObservable(obj);
if (val !== null && typeof val === 'object') {
for (var i in val) {
if (val.hasOwnProperty(i)) objProperties.push({ "name": i, "value": val[i] });
}
}
return objProperties;
};
ko.extenders.trackChange = function (target, track) {
if (track) {
target.isDirty = ko.observable(false);
target.originalValue = target();
target.subscribe(function (newValue) {
// use != not !== so numbers will equate naturally
target.hasValueChanged(newValue != target.originalValue);
target.hasValueChanged.valueHasMutated();
});
}
return target;
};
var applyChangeTrackingToObservable = function (observable) {
// Only apply to basic writeable observables
if (observable && !observable.nodeType && !observable.refresh && ko.isObservable(observable)) {
if (!observable.isDirty) observable.extend({ trackChange: true });
}
};
var applyChangeTracking = function (obj) {
var properties = getObjProperties(obj);
ko.utils.arrayForEach(properties, function (property) {
applyChangeTrackingToObservable(property.value);
});
};
var getChangesFromModel = function (obj) {
var changes = null;
var properties = getObjProperties(obj);
ko.utils.arrayForEach(properties, function (property) {
if (property.value != null && typeof property.value.isDirty != "undefined" && property.value.isDirty()) {
changes = changes || {};
changes[property.name] = property.value();
}
});
return changes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment