我在使用knockout-validation扩展名的ASP.NET应用程序上使用KnockoutJS。
我有父视图和子视图模型。我需要在子viewModel中的一个字段仅在父viewModel中的字段的值为X时才需要。
这是我目前所拥有的,但这不起作用:
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: false,
decorateElemen: true,
messageTemplate: null,
grouping: {
deep: true,
live: true,
observable: true
}
});
var childVM = function (data, selected, parent) {
var self = this;
self.parent = ko.observable(parent);
self.ChildField = ko.observable();
self.isSelected = ko.computed(function () {
return self === selected();
}, self);
// validation
self.validationObject = ko.validatedObservable({
ChildField: self.ChildField.extend({
required: {
onlyIf: function () {
console.log(self.parent().ParentField());
return self.parent().ParentField() == 2;
}
}
}),
});
}
var ParentVM = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.ParentField = ko.observable();
self.children = ko.observableArray([]);
self.children.push(new ChildVM({ }, self.selectedTab, self));
// Validation
self.validationObject = ko.validatedObservable({
Children: self.children
});
self.save = function () {
if ( self.errors().length === 0 ) {
self.errors.showAllMessages(false);
} else {
self.errors.showAllMessages();
return false;
};
var raw = ko.mapping.toJS(self, mapping);
return $.ajax({
// foo
});
}
}
控制台日志在viewModel初始化时输出值,而不是在执行save函数并运行验证时输出?