0

I'm beginning to play with Knockout.JS and I'm trying to compute a sum of 'points' across valid fields in my viewmodel, but have no idea how to go about this. The idea is that as the form is filled I can display a smart progress bar based on the completed value of points each validated field contains.

How would I setup dynamicpoints to always contain a live sum of the fields?

Brief snippet of the view model:

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 { ??? }
})
Jonathan
  • 419
  • 6
  • 15

2 Answers2

0

try this:

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;
    }
});
RodneyTrotter
  • 1,166
  • 7
  • 8
  • That will not work correctly. The problem is that 'error' is not an ko.subscribable (neither observable nor computed). Therefore knockout can not detect changes to its value and the computed will not be updated. – delixfe Jan 29 '13 at 08:00
  • Fair enough. I overlooked that, sorry. – RodneyTrotter Jan 30 '13 at 20:09
0

knockout-validation extends validatable observables with a ko.computed 'isValid'.

Therefore you could solve that like:

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;
};
delixfe
  • 2,471
  • 1
  • 21
  • 35