Knockout.JS验证和计算仅验证的字段

时间:2013-01-29 01:36:15

标签: knockout.js knockout-validation

我开始玩Knockout.JS,我正在尝试在我的视图模型中的有效字段中计算“点”的总和,但不知道如何去做。我的想法是,当表单填写完毕后,我可以根据每个验证字段包含的点的完整值显示智能进度条。

如何设置 dynamicpoints 以始终包含字段的实时总和?

视图模型的简短摘要:

myViewModel = ko.validatedObservable({
 fields: {
  firstname: {
        label: "First Name",
        value: ko.observable("").extend({
              required: true
            }),
        points: 100
  },
  lastname: {
        label: "LastName",
        value: ko.observable("").extend({
              required: true, 
              minLength: 2
            }),
        points: 200
  }
 }
 dynamicpoints: ko.computed { ??? }
})

2 个答案:

答案 0 :(得分:0)

试试这个:

myViewModel = ko.validatedObservable({
    fields: {
        firstname: {
            label: "First Name",
            value: ko.observable("").extend({
                  required: true
                }),
            points: 100
        },
        lastname: {
            label: "LastName",
            value: ko.observable("").extend({
                  required: true, 
                  minLength: 2
                }),
            points: 200
        }
    },
    dynamicpoints: ko.computed(function(){
        var totalPoints = 0;

        if(!myViewModel.fields.firstname.value.error)
            totalPoints += field.points;

        if(!myViewModel.fields.lastname.value.error)
            totalPoints += field.points;

        return totalPoints;
    }
});

答案 1 :(得分:0)

knockout-validation使用ko.computed'isValid'扩展了可验证的observable。

因此你可以解决这个问题:

var dynamicpoints = ko.computed(function(){
    var totalPoints = 0;

    if(!myViewModel.fields.firstname.value.isValid())
        totalPoints += field.points;

    if(!myViewModel.fields.lastname.value.isValid())
        totalPoints += field.points;

    return totalPoints;
};