简体   繁体   中英

KnockoutJS and computed binding on array

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?

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/

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM