I have a Knockout View with about 50 inputs of various kinds. I already track when a change was made to the model by the following code
self.Changed = ko.computed(function() {
return ko.toJS(self.Outing);
});
And then subscribing to the Changed function to save the model back to the server. What I would like to accomplish is when a user changes an individual input it triggers a css binding on that input to highlight it so the user knows what he/she changed. How can I do this with out individually subscribing to each observable property?
There are a few ways that you could handle something like this. A convenient way to do this might be a custom binding that grabs the original value and sets up a css binding against a computed that looks at the original vs. current value.
Maybe something like:
ko.bindingHandlers.changedCss = {
init: function(element, valueAccessor, allBindings) {
var original, isDirty, data, cssClass, binding;
data = allBindings().value;
original = ko.utils.unwrapObservable(data);
isDirty = ko.computed({
read: function() {
return ko.utils.unwrapObservable(data) !== original;
},
disposeWhenNodeIsRemoved: element
});
cssClass = ko.utils.unwrapObservable(valueAccessor());
binding = { css: {} };
binding.css[cssClass] = isDirty;
ko.applyBindingsToNode(element, binding);
}
};
You would use it like: <input data-bind="value: first, changedCss: 'changed'" />
So, the idea is that we look for what the value binding is bound against and set up a computed observable on-the-fly to give us a dirty flag for this property. Then, programmatically add a css binding using the class name that was passed to the binding.
http://jsfiddle.net/rniemeyer/PCmma/
Alternatively, you could create an extension that would let you add this dirty tracking from the view model side. This would give you some additional flexibility, like the ability to reset the tracking (consider the current value to be clean). For starters, you could do something like:
ko.subscribable.fn.trackDirtyFlag = function() {
var original = this();
this.isDirty = ko.computed(function() {
return this() !== original;
}, this);
return this;
};
Then, use it like: this.first = ko.observable("John").trackDirtyFlag();
http://jsfiddle.net/rniemeyer/JtvWd/
You could then do things like add a reset method that sets original equal to the current value.
If your goal is just to be able to color the dirty fields, then the custom binding might be a good choice, as you don't need to change your view model at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With