【发布时间】:2015-11-23 13:12:35
【问题描述】:
如何将 ko.validation 与 ko.utils 扩展一起使用?
这是我尝试过的,我认为作为 JS 的新手,我可能会犯一个基本错误(我遇到的错误在 cmets 中):
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 & revert。
所以我要问的是我在这里犯了一个愚蠢的错误,有人可以解释一下这应该如何工作。
【问题讨论】:
标签: javascript knockout.js prototype knockout-validation