Simon Luhur
Simon Luhur

Reputation: 35

Knockout matrix

I am trying to make a matrix matching table using knockout, but I'm stuck regarding the compare between the current data-bind and the parent data-bind.

Here is the jsfiddle.net/wup9rxeu/4/

<script type="text/html" id="cubeheader-template">
<th data-bind="text: $data.Name"></th>
</script>

<script type="text/html" id="body-template">
<!-- ko foreach: $parent.modeldim -->
<td>x</td>
<!-- /ko -->
</script>

What I want to accomplished is that when the table is populated with x and - for each td, based on the modelcubdim data.

I need some pointer on comparing the ID against the parent ID and if it's a match, then X or else -

Thanks

Upvotes: 1

Views: 690

Answers (1)

Rango
Rango

Reputation: 3907

You can expand your model with transformed data to represent every cell in the table.

// just for easy searching items by its ID
data.itemById = function(arr, id){
    return ko.utils.arrayFirst(arr, function(item){
        return item.ID == id;
    });
};

// the property that will hold actual data for *every* table row
// in the format { Name: [Cub Name], Data [array of "x" and "-"] }
data.series = ko.utils.arrayMap(data.modelcub, function(cub){
    var cubdim = data.itemById(data.modelcubdim, cub.ID);
    return {
        Name: cub.Name,
        Data: ko.utils.arrayMap(data.modeldim, function(dim){
            var item = cubdim && data.itemById(cubdim.CubeDimension, dim.ID);
            return item ? "x" : "-";
        })
    };
});

Then slightly change your markup:

<tbody data-bind="foreach: series">            
<tr> 
    <th data-bind="text: Name"></th>  
    <!-- ko foreach: Data -->
    <td data-bind="text: $data"></td>
    <!-- /ko -->
</tr>
</tbody>

And you will get it working like here: http://jsfiddle.net/wup9rxeu/5/

Upvotes: 1

Related Questions