3

I am not sure why my foreach sections isn't working? The very first data-bind text: Id is working though.

Knockout:

import Knockout from 'knockout';

function ViewModel() {
    var self = this;
    self.Id = ko.observable();
    self.Sections = ko.observableArray();
};

var viewModel = new ViewModel();

ko.applyBindings(viewModel);

$.getJSON("/api/projects/3455", function(data) {
    console.log(data);
    viewModel.Id(data.Id);
    viewModel.Sections(data.Sections);
});

HTML:

<div data-bind="text: Id">
    <div data-bind="foreach: Sections">
        <div data-bind="text: Id"></div>  
    </div>
</div>

Returned JSON:

enter image description here

0

1 Answer 1

3

The problem is in your html with the first text binding because it replaces the whole content of your top level div element and you lose your foreach.

So you need to move the text binding inside your top div:

<div>
    <div data-bind="text: Id"></div>
    <div data-bind="foreach: Sections">
        <div data-bind="text: Id"></div>  
    </div>
</div>

Or using the containerless binding syntax if you don't like to have the extra div:

<div>
    <!-- ko text: Id --><!-- /ko -->
    <div data-bind="foreach: Sections">
        <div data-bind="text: Id"></div>  
    </div>
</div>
Sign up to request clarification or add additional context in comments.

4 Comments

Ooh, well-spotted, that's unpredictable view code in the question's post. However, even though I would've also expected the behavior you suggested, it seems that with nor without a top level Id the contents are overwritten. Any thoughts on that?
@Jeroen it does not matter what you have in your Id initially. The KO text binding "sets the element’s content to a text node with your parameter value. Any previous content will be overwritten." so the inner elements are lost at the moment when you call ko.applyBindings
Ah yes, you're right, I didn't interpret my own example correctly. My bad!!
s/loose/lose/

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.