Pregunta

I've created an example of the problem here:

http://jsfiddle.net/JustinN/qWeLT/1/

My actual code is hooked up to an ASP.NET web method, so the example code has been tweaked to point at a public web service to demonstrate.

Basically, I have an array which I bind to, however after an ajax call, the table does not show the updated information. I'm not sure what I am missing, I thought at first I needed the mapping plugin, so I've tried that but am still not getting anywhere.

Surely I'm not meant to applyBindings every time my data changes?

[EDIT]

JavaScript below:

var ViewModel = function () {
var self = this;
self.items = ko.observableArray([]);
self.refresh = function () {
    $.ajax({
        type: "POST",
        url: "http://api.wipmania.com/json",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            ko.mapping.fromJS(data.d, self.items.address);
        }
    });
};
}

var viewModel = new ViewModel();
$(function () {
ko.applyBindings(viewModel);
viewModel.refresh();
});

HTML below:

<table data-bind="visible:items.length > 0">
<thead>
    <tr>
        <th>Country</th>
        <th>Code</th>
    </tr>
</thead>
<tbody data-bind="foreach: items">
    <tr>
        <td data-bind="text:country"></td>
        <td data-bind="text:country_code"></td>
    </tr>
</tbody>
</table>
¿Fue útil?

Solución

Check out this fiddle: http://jsfiddle.net/Gm7zH/1/

First of all I am using fake ajax data because of cross domain request. That's the data I got from your server. And using a setTimeout to simulate the async request.

Then you do a number of errors:

You try to map to property address of array, which does not exist. Second the address of your result is just a object, so I wrap it in an array to make it work.

Then you try to map to an existing observableArray, but supplying the array as the second argument, the second argument is the mapping options, the third is the correct place for that. I pass null as the mapping options in my example.

Lastly, for the table to be visible you say items.length > 0. What you want is items().length > 0 which is the length of the underlying array.

Otros consejos

Your array is self.items, but your ajax success call is updating self.items.address, which I'm guessing is undefined. So the mapping plug-in is creating a new model, unrelated to the original.

(You haven't shown what data.d looks like, but I'm assuming it's an array.)

Surely I'm not meant to applyBindings every time my data changes?

Correct. You do that once, then updating the observables should (all being well) update the DOM.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top