1

I have a viewmodel like

AppViewModel = {
    agent : ko.observableArray([ {
        name : 'test',
        age  : '23'             
    }])         
};

My json data comes like

{"agent":[{"name":"john","age":"23"},{"name":"conor","age":"23"}]}

for ajaxcall every 3 sec

I could able to replace the observable array like [from here]

success : function(responseData) {
    var data = ko.toJS(responseData);  
     AppViewModel.agent(data.agent);
}

Some times the json data comes like

{"agent":[{"name":"john"}]}

without age, in this case the incomplete data stays with the observable array

and getting script error as

'age' is undefined in databinding

even after new response arrives like {"agent":[{"name":"john","age":"23"}]}

I want whole obsevable array to replaced with new data.

Thanks

EDIT:

enter image description here

DataBinding:

<!-- ko foreach: agent-->
    <tr>                                
        <td style="font-weight:bold;" data-bind="text: name"></td>      
        <td style="font-weight:bold;" data-bind="text: age"></td>
    </tr>
<!-- /ko -->
2
  • Where do you get the error in your javascript or in render process ? Can you post your view ? Commented Dec 2, 2013 at 13:57
  • @Damien I have given the View Commented Dec 2, 2013 at 14:10

1 Answer 1

0

If you prefix your property with the $data special binding context property then KO won't complain if the given property does not exists.

So if you write $data.age then you don't get an error if the server sends an object without the age property:

<tr>
    <td style="font-weight:bold;" data-bind="text: $data.name"></td>
    <td style="font-weight:bold;" data-bind="text: $data.age"></td>
</tr>

Demo JSFiddle.

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.