我是新來使用knockout,我試圖使用knockout驗證插件與地圖插件一起使用。我在視圖模型對象上遇到了isValid函數的問題。根據文檔isValid應該返回一個布爾值來確定視圖模型上的任何可觀察對象是否有效,但是當我調用它時,我得到一個錯誤,指出isValid不是一個函數。但是,如果我在observables自己上調用isValid,它可以正常工作。問題是我使用映射插件和一些從服務器獲得的動態數據對象,所以我不一定知道需要驗證的觀察對象的名稱,因此單獨驗證它們是不可行的。下面的例子被簡化了,但在真正的實現中,我不知道可觀察對象的名字。也許我錯過了一些文檔?Knockout ViewModel在使用Knockout驗證插件時有錯誤
謝謝你的時間。
這樣確實
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'));