Juan
Juan

Reputation: 125

Knockout.js ObservableArray not binding

I have this code as global for the whole page:

<script type="text/javascript">
    var data = [];
    var VM_FiltroSeguros =
        {
            seguros: ko.observableArray(data)
        };
    ko.applyBindings(VM_FiltroSeguros.seguros);
</script>

Then when a succesfull ajax call is made, executed this:

function okFiltrarSeguros(data)
    {
        var parsedData = parse(data);
        if (parsedData.Ok)
        {
            toastr.success('Se encontraron ' + parsedData.Value.length.toString() + ' Seguros.');

            $('#liResultsFiltroSeguro').show();

            VM_FiltroSeguros.seguros = parsedData.Value;
};

The Html is these:

<table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Ramo</th>
                            <th>Poliza</th>
                        </tr>
                   </thead>
                   <tbody data-bind="foreach: seguros">
                     <tr>
                       <td><span data-bind="text: NroRamo"></span></td>
                       <td><span data-bind="text: NroSeguro"></span></td>
                     </tr>
                   </tbody>
                  </table>

After VM_FiltroSeguros.seguros = parsedData.Value; is executed I can see in the debugger that the viewModel is filled whith objects, but the is never updated. What could be wrong? Thanks!!!!

Upvotes: 2

Views: 699

Answers (1)

badsyntax
badsyntax

Reputation: 9650

There's a couple of things you're doing wrong here. First, you need to bind the entire ViewModel:

var data = [];
var VM_FiltroSeguros =
{
   seguros: ko.observableArray(data)
};
ko.applyBindings(VM_FiltroSeguros);

Then you need to add data to the 'seguros' property with a function call like this:

VM_FiltroSeguros.seguros(parsedData.Value);

Upvotes: 4

Related Questions