0
votes

I am new to Knockoutjs, and I need some help to properly bind the data.

I want knockoutjs to fill out each div after AJAX call completes and the data from server looks like following:

{
    name: 'michael',
    phone: '123456789',
    friends:
    [
        { sex: 'male', region: 'europe' },
        { sex: 'female', region: 'america' },
        { sex: 'male', region: 'asia' }
    ]
}

FYI, I want to bind above data WITHOUT using foreach to iterate and fill out 'friends' above. Instead, for some reason, I want to bind the data manually on each div, eg)

<div data-bind: friends[0].sex>...
<div data-bind: friends[1].sex>...
<div data-bind: friends[2].sex>...

Here's my JSfiddle: http://jsfiddle.net/VAcQB/

And it currently has error saying like:

Uncaught Error: Unable to parse bindings.
Message: TypeError: Cannot read property '0' of undefined;
Bindings value: text: data.friends[0].sex 

I think it's because it does not understand the binded data because the data is not available yet when the page loads.

Can someone please help to solve the issue? Thank you so much in advance.

1
"...for some reason, I want to bind the data manually..." - would you explain what's better in doing this manually? - Tomalak

1 Answers

0
votes

You should check that data is not null. The best way to do this is to use with binding:

<div data-bind="with: data">
 ... Your content
</div>

Here is working fiddle: http://jsfiddle.net/VAcQB/2/