I’ve gotten an requirement that all numeric columns in our knockout grid should have red color if they are negative to warn the user.
I could do it with standard bindings, but it would add a lot of code to the viewmodel and view.
I use the knockout validation framework and they use extenders to add validation.
I want to do the same, I’ve looked at the extender examples, but they require you do add elements to the view, Somehow the validation framework works with only extenders, how can I do the same? My goal is to only need something like this to add the warning
this.accountBalance = ko.observable(data.AccountBalance).extend({ warnIfNegative: true });
Update: I did this after looking at the validation framework, what I dont like is that you need to override each binding to get it to work, for example i want this both for text and value binding
(function () {
ko.extenders.negativeValueWarning = function (target, option) {
target.hasWarning = ko.observable();
function warn(newValue) {
target.hasWarning(newValue < 0 ? true : false);
}
warn(target());
target.subscribe(warn);
return target;
};
var init = ko.bindingHandlers.text.init;
ko.bindingHandlers.text.init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if (init)
init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
var value = valueAccessor();
if (value.hasWarning) {
ko.applyBindingsToNode(element, { negativeValueWarning: value.hasWarning });
}
};
ko.bindingHandlers.negativeValueWarning = {
update: function (element, valueAccessor) {
var warn = ko.utils.unwrapObservable(valueAccessor());
if (warn)
$(element).addClass("negative-warning");
else
$(element).removeClass("negative-warning");
}
};
} ());
I ended up doing this, what do you guys think?
http://jsfiddle.net/ZYyEw/25/
Update: Using computed instead of subscribe