【问题标题】:Using Knockout Validation with knockout.utils.extend将 Knockout 验证与 knockout.utils.extend 一起使用
【发布时间】: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


    【解决方案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 });
    

    这里有一个小提琴给你看:

    http://jsfiddle.net/2wLL3exc/

    【讨论】:

    • 感谢您的澄清,我仍然收到错误,但我认为它与 ko.validation 有关,当我设置 parseInputAttributes: false 时错误停止(但验证也是如此)。
    • 您是否有机会将其纳入您的问题或在小提琴中重现它?如果没有看到更多问题,很难进一步提供帮助。
    • 您回答了这个问题,非常感谢,我的应用程序在验证方面存在其他问题(模板中的表单无法验证),因此我目前正在更新我的应用程序以使用 ko.bindinghandlers 作为模态(我使用的是 knockstrap使用模板)试图变得聪明让我付出了代价。顺便说一句,我在雷特福德的小世界离谢夫不远。再次感谢
    猜你喜欢
    • 2017-02-20
    • 2013-03-24
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    相关资源
    最近更新 更多