0

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

我将如何设置动态点以始终包含字段的实时总和?

视图模型的简短片段:

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 { ??? }
})
4

2 回答 2

0

淘汰赛验证用 ko.computed 'isValid' 扩展了可验证的 observables。

因此,您可以像这样解决:

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;
};
于 2013-01-29T07:57:52.630 回答
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;
    }
});
于 2013-01-29T03:40:49.403 回答