Knockout array of arrays

2019-07-20 17:44发布

问题:

The incomming data is like this [[1,2,3],[4,5,6]] and sometimes it is like this [[1,2],[4,5]]. Here is the HTML.

<button data-bind="click: refreshJSON">Test</button>
<table>
    <tbody data-bind="foreach: array">
        <tr data-bind="foreach: subarray">
            <td data-bind="text: $data"></td>
        </tr>
    </tbody>
</table>

<script type="text/javascript">


    var ViewModel = {

        tableModel : ko.observableArray([[1,2,3],[4,5,6]]),

        refreshJSON : function(){
            this.tableModel([[1,2],[4,5]]);
        }

    };

    ko.applyBindings(ViewModel);

</script>

I'm guessing I have to use ko.observableArray() on each of the subarrays however I'm unclear on how to do this, or how to do the data-binds in the HTML.

回答1:

Update: Removed the observableArray inside an observableArray bit. Apparently that doesn't work. Just bind your outer collection.

The binding part is fairly easy:

<div data-bind="foreach: tableModel">
    <div data-bind="foreach: $data">
        <span data-bind="text: $data"></span>
    </div>
</div>


标签: knockout.js