在 knockout.utils.extend 中使用 Knockout 验证

Using Knockout Validation with knockout.utils.extend

如何使用 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。要修复您的代码,请执行:

// Set it
this.Email(data.Email);
// Then extend it
this.Email.extend({ required: true, email: true });

这里 fiddle 向您展示:

http://jsfiddle.net/2wLL3exc/