Last active
January 3, 2016 00:49
-
-
Save beyond-code-github/8385560 to your computer and use it in GitHub Desktop.
Change tracking for flat viewmodels, all properties must be observables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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