2

I'm having troubles getting the binding working for a nested array. The values are displaying correct when the page first loads, but when I make edits, bound objects do not update.

I've created a jsfiddle here: http://jsfiddle.net/coverbeck/qCzT6/1/.

My HTML is this:

<body>
    <ul>
<!-- ko foreach: {data: cities, as: 'city'} -->
        <li>
           <input data-bind="value: city.name"/>
           <span data-bind="text: city.name"></span>
        </li>
    <ul>
    <!-- ko foreach: {data: neighborhoods, as: 'neighborhood'} -->
        <li>
            <input data-bind="value: neighborhood"/>
            <span data-bind="text: neighborhood"></span>
        </li>
    <!-- /ko -->
    </ul>
<!-- /ko -->
</ul>
</body>

And my JavaScript is:

var sf = {name: ko.observable('San Francisco'),
          neighborhoods: ko.observableArray([
                ko.observable('Haight'), 
                ko.observable('Bayview'), 
                ko.observable('Marina')
           ])
         }; 
var ny = {name: ko.observable('New York'),
          neighborhoods: ko.observableArray([
                ko.observable('Hells Kitchen'), 
                ko.observable('Times Square')
            ])
          };

var cities = ko.observableArray([sf, ny]);
var viewModel = { cities: cities };
ko.applyBindings(viewModel);

When I modify city names, the corresponding span element updates. When I modify neighborhood names, the corresponding span element does not update.

I asked a similar question already here, and the answer worked. I seem to be running into the same problem all over again, except this time it's a nested array where I'm seeing the problem. I tried the fix from that answer against the nested array, but it didn't seem to make a difference in this case.

Thanks,

Charles

2
  • Man, your code formatting is atrocious. Can you even read that? Commented Mar 19, 2013 at 15:50
  • "Atrocious" seems a little harsh, but I updated the formatting. Commented Mar 19, 2013 at 16:49

1 Answer 1

2

I'm not sure exactly where your problem is coming from, but it can be solved like this:

var ny = {name: ko.observable('New York'), 
          neighborhoods: ko.observableArray([
              new neighborhood('Hells Kitchen'), 
              new neighborhood('Times Square')])};

function neighborhood(name) {
    this.name = ko.observable(name);
}

Then you bind foreach neighborhoods and then bind to name. The problem might be that it doesn't like the observable that doesn't have a name?

Working fiddle here

Sign up to request clarification or add additional context in comments.

Comments

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.