3

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 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

4 Comments

There's no need to add the items individually, just set the tableModel directly. But anyway, the bindings just needed to be corrected.
Currently, Knockout doesn't work so well with observableArray inside of observableArray list this. Like Jeff said, you only need the outer observableArray, and just set it to outerArray. See this issue.
@JeffMercado: I haven't tried it, but if you have an array inside of an observableArray, will it see removal and additions to the inner array? I would assume not. But I guess (according to Michael) it doesn't work to have an observableArray inside an observableArray anyway.
To be able to see any changes to any object, you would have to put it inside an observable. If the inner arrays were not made observable, you wouldn't see changes made to them. However since the outer array was made observable, you'd see changes to that. And yes, you can have an observable array within another, it's just that in this case, it probably isn't needed.

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.