Question

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 -->
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top