digitzfone
digitzfone

Reputation: 43

Cannot bind ko.observable array to foreach loop

I have a simple viewModel that I am creating from a MVC for to json string, I am using ko.mapping to accomplish this.

var initialTicketData = {"Ticket": [{"ID":1,"EventID":506596,"Name":"General Admission","Quantity":100,"Price":15.0},{"ID":2,"EventID":506596,"Name":"Backstage Passes","Quantity":25,"Price":50.0}]};

var ticketViewModel = ko.mapping.fromJS(initialTicketData);

ko.applyBindings(ticketViewModel);

I want to iterate through this array and display the data on the page. I am trying to use a foreach data-binding.

<tbody data-bind="foreach: ticketViewModel.Ticket">
    <tr>
        <td data-bind="text: ticketViewModel.Name"></td>
        <td data-bind="text: ticketViewModel.Price"></td>
        <td data-bind="text: ticketViewModel.Quantity"></td>
    </tr>
</tbody>

However, when I try to run I get the following error.

"Unable to parse bindings. Message: ReferenceError: ticketViewModel is not defined; Bindings value: foreach: ticketViewModel.Ticket"

Any help would be greatly appreciated.

Upvotes: 0

Views: 2408

Answers (1)

John Earles
John Earles

Reputation: 7194

Try this instead:

<tbody data-bind="foreach: Ticket">
    <tr>
        <td data-bind="text: Name"></td>
        <td data-bind="text: Price"></td>
        <td data-bind="text: Quantity"></td>
    </tr>
</tbody>

Bindings are always relative to the current context. When you say ko.applyBindings(ticketViewModel); you set the "root" context to ticketViewModel. Then when you use a 'foreach' you add a new context, and bindings inside the 'foreach' are now relative to each Ticket element.

Upvotes: 1

Related Questions