0

I’m currently trying to calculate a total flooring space using a form and the KnockoutJS tools. All has been setup and it’s working to the point of the calculation of the total floorspace.

The JsFiddle: http://jsfiddle.net/rmfloris/zmc0nzrr/24/

The visitor can add up to 4 differente spaces(self.ruimtes), which all need to be calculated to get to a total floorspacing (this.totaalOppervlakte). I have setup a computed function for the total floorspacing and a loop within this to go through all the ‘ruimtes’. When I run the code and use console.log it seems that it doesn’t loop through the array, which makes sense as the array is empty on start. But when I make a change to the array via the self.ruimtes.push() function, still nothing is happening.

this.totaalOppervlakte = ko.computed(function() {
    var total = 0;
    $.each(self.ruimtes, function() {
        console.log('calculation')
        total = total + self.Oppervlakte();
    });
    return total.toFixed(2);
});

Any idea why the ko.computed isn’t working as expected?

2 Answers 2

2

You have several problems in that code. First off the computed totaalOppervlakte is outside the scope of the ViewModel, so self does not equal what you think it does. Secondly, your usage of $.each seems to be off. I would imagine you are looking for something more like this:

var total = 0;
$.each(self.ruimtes(), function(ruimte){
    total += ruimte.Oppervlakte();
});

The main differences are:

  1. self.ruimte seems to be a typo and should be self.ruimtes

  2. self.ruimtes is a knockout observable and must be unwrapped -> self.ruimtes()

  3. You are missing the arguments in your callback.

You can checkout the correct usage of $.each here: http://api.jquery.com/jquery.each/

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry but plz do this: total += ruimte.Oppervlakte(); It hurts my eyes!!
Was keeping changes to a minimum, but if you insist.
0

You're trying to iterate on the observableArray using jQuery's array iterator (each). The observableArray is not an array, it contains an array. You need to get the array value out before trying to iterate.

$.each(self.ruimte(), function() {

Also, shouldn't that be self.ruimtes?

2 Comments

Thanks for pointing that out. I have update the code and the information in the start post. once I add the backets () to the line, I get the error 'Uncaught TypeError: self.ruimtes is not a function'
You defined totaalOppervlakte outside your viewmodel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.