如何在ko.utils扩展中使用ko.validation?
这是我尝试过的,我认为因为我是一个相当新的JS,我可能会犯一个基本的错误(错误即将到来的评论):
var Customer = function (data) {
var cus = this;
cus.FirstName = ko.observable();
cus.LastName = ko.observable();
cus.Email = ko.observable();//.extend({ required: true, email: true });
// above line causes 'Uncaught TypeError: observable.extend is not a function'
//extenders
this.cleanData = data;// copy of original Customer
this.initData(data);//call your prototype init function
};
// Extend the Customer object to init with data & also so we can revert back to original if user cancel's
ko.utils.extend(Customer.prototype, {
initData: function (data) {
this.FirstName(data.FirstName);
this.LastName(data.LastName);
this.Email(data.Email).extend({ required: true, email: true });
// above line causes 'this.Email(...).extend is not a function'
},
revert: function () {
this.initData(this.cleanData);
}
});
如果我在Customer对象中删除了ko.utils.extend(在进程中丢失init / revert),则下面的代码可以正常工作:
var Customer = function (data) {
var cus = this;
cus.FirstName = ko.observable(data.FirstName);
cus.LastName = ko.observable(data.LastName);
this.Email(data.Email).extend({ required: true, email: true });// works fine - but weve lost 'ko.utils.extend' functionality
};
不幸的是,正如我所说,我正在失去init和恢复我需要的。
所以我要问的是,我在这里犯了一个愚蠢的错误,有人可以解释一下这应该如何运作。
答案 0 :(得分:1)
错误就在你的initData方法中。这一行没问题:
cus.Email = ko.observable();//.extend({ required: true, email: true });
这个位不起作用:
this.Email(data.Email).extend({ required: true, email: true });
您可以通过ko.observable
函数使用extend,但是您不能在设置observable的结果上使用.extend。要修复代码,请执行以下操作:
// Set it
this.Email(data.Email);
// Then extend it
this.Email.extend({ required: true, email: true });
这是向你展示的小提琴: