I have a situation here for the knockout with for each binding with customization
Here is my code:
<div id="content-wrapper">
<div id="akjsdbgb">
<table>
<tbody data-bind="foreach: resultData">
<tr>
<td data-bind="text: fieldName"></td>
<td data-bind="text: fieldValue"></td>
</tr>
</tbody>
</table>
</div>
</div>
Model:
self.resultData = ko.observableArray([]);
self.getResultData = function () {
var data = Cobalt.Data.getResultData();
self.resultData(data.searchDataList);
};
};
Models.Field = function(data) {
var self = this;
self.fieldName = data.fieldName;
self.fieldValue = data.fieldValue;
};
The problem is i need to create a tabular data from the resultData which is in fieldName and fieldValue formats and the table should be having two sets of data in a single tr means
4 's in a tr but the data array contains single fieldName and fieldValue; so we need to loop in a tr for two times of data and then increment it.
OUTPUT AS EXPECTED:
You could create a computed which would pair items, something like the following:
You would then bind to the
rows
property instead of binding directly to theresultData
property.EDIT: @GOK asked, in a comment, for a version which would allow customizable number of items in a single row.
You could achieve this easily by doing something like the following:
Each row would then have properties named
item1
,item2
, etc, to the number of items set by theitemsOnEachRow
observable (some of these properties might hold a null reference, if the total item count isn't evenly divisible by the items per row count).I have written a sample on this, which you can find on http://jsfiddle.net/af7P2/, but I do not suggest binding the table in the way it is done in that sample. I'm not sure how it would set up subscriptions, but it might subscribe a multitude of times to the
columns
computed, one time for each row. It's just there to show a sample of therows
computed, not for anything else.If you want each row to be an array in itself, you could do it with the following code:
The bindings for this version (which you can find at http://jsfiddle.net/af7P2/1/) is a bit better, since it doesn't use the
columns
computed one time for each row.In general, this solution might not perform very well, depending on your situation. Any addition/removal of items to the
resultData
array, or a change to theitemsOnEachRow
value, would rebind the whole table. Might not be a problem for you, just something to be aware of.