Frank van Eykelen Frank van Eykelen - 9 months ago 64
Javascript Question

How do I copy an item from a ko.mapping.fromJS Array to another property of the viewmodel?

Here's something that used to work in existing code that ran on Knockout 2, that I'm refactoring to Knockout 3.

The properties of the viewmodel are initialized from a feed (simplified code):

url: "/api/GetData",
data: {
clientId: clientId
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
traditional: true,
success: function (data) {
viewModel.selectedPeriod = ko.observable(viewModel.periods()[0]);
async: false

viewModel.selectedPeriod =
line works when I debug the value, but the binding does not work.

So this fails ...

<ul data-bind="foreach: selectedPeriod.Years">
<li data-bind="text: Year"></li>

... while this works:

<ul data-bind="foreach: periods">
<ul data-bind="foreach: Years">
<li data-bind="text: Year"></li>

I've reproduced my problem in a simplified Fiddle:

Answer Source

Just a few changes to your code ...

viewModel.selectedPeriod(viewModel.periods()[0]); // observable method call instead of assigning


 <ul data-bind="foreach: selectedPeriod().Years">  // resolve the observable first ... 

a working code can be found here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download