我是使用淘汰赛的新手,我正在尝试将淘汰赛验证插件与映射插件一起使用。我在视图模型对象上遇到了 isValid 函数的问题。根据文档,isValid 应该返回一个 bool 以确定视图模型上的任何可观察对象是否有效,但是当我调用它时,我收到一个错误,指出 isValid 不是函数。但是,如果我对可观察对象本身调用 isValid ,它就可以正常工作。问题是我正在使用映射插件以及从服务器获取的一些动态数据对象,因此我不一定知道需要验证的可观察对象的名称,因此单独验证它们是不可行的。下面的示例已简化,但在实际实现中我不知道可观察对象的名称。也许我'
谢谢你的时间。
这确实有效
var dataItem = { FirstName: '', LastName: '', Age: '', Email: '' }
var viewModel = function(data) {
var self = this;
this.Email = ko.observable().extend({ email: true });
this.LastName = ko.observable().extend({ required: true });
this.Age = ko.observable().extend({ required: true, min: 0 });
this.saveClick = function () {
if (!self.Email.isValid() || !self.Age.isValid() || !self.LastName.isValid()) {
alert('Not valid');
else {
alert('Valid');
}
};
this.cancelClick = function () {
ko.mapping.fromJS(dataItem, null, this);
}
ko.mapping.fromJS(data, {}, this);
};
var viewModelInstance = new viewModel(dataItem);
ko.applyBindings(viewModelInstance, document.getElementById('bindingDiv'));
但这不起作用
var dataItem = { FirstName: '', LastName: '', Age: '', Email: '' }
var viewModel = function(data) {
var self = this;
this.Email = ko.observable().extend({ email: true });
this.LastName = ko.observable().extend({ required: true });
this.Age = ko.observable().extend({ required: true, min: 0 });
this.saveClick = function () {
//TODO: according to the documentation you should be able to just
//check self.isValid() but that throws an error that there is no
//such method on the object? dunno why.
if (!self.isValid()) {
alert('Not Valid');
}
else {
alert('Valid');
}
};
this.cancelClick = function () {
ko.mapping.fromJS(dataItem, null, this);
}
ko.mapping.fromJS(data, {}, this);
};
var viewModelInstance = new viewModel(dataItem);
ko.applyBindings(viewModelInstance, document.getElementById('bindingDiv'));