gpt4 book ai didi

javascript - 将 Knockout 验证与 knockout.utils.extend 结合使用

转载 作者:行者123 更新时间:2023-11-27 23:56:18 24 4
gpt4 key购买 nike

如何将 ko.validation 与 ko.utils 扩展一起使用?

这是我尝试过的,我认为由于我对 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
};

不幸的是,正如我所说,我失去了我需要的初始化和恢复。

所以我问的是我在这里犯了一个愚蠢的错误吗?有人可以解释一下这应该如何工作吗?

最佳答案

问题出在你的 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 });

这里有一个 fiddle 向您展示:

http://jsfiddle.net/2wLL3exc/

关于javascript - 将 Knockout 验证与 knockout.utils.extend 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com