问题
I am trying to use below data for KO mapping
I try to initialise it using ajax success event in document.ready
var organisationData = data.d; var orgObject = { organisationsData: organisationData };
var newviewmodel = ko.viewmodel.fromModel(orgObject);
The problem is ajax is taking much longer time to load and then the javascript error pops up saying the viewmodel doesnt exist.
So
How can I tell Knockout to rebind once the ajax has successfully loaded
Is there anyway I can tell KO not to bind/ hide the table when the data I got from ajax is empty?
Continued from Using KnockoutJS automatic binding
回答1:
I made a fiddle in which I replaced the server call with a timer.
JS:
var vm = {
items: ko.observableArray()
};
ko.applyBindings(vm);
setTimeout(function(){
var rawData =[
{name:'item1'},
{name:'item2'},
];
ko.mapping.fromJS(rawData, {}, vm.items);
// to ensure that name is an observable
var item1Name = vm.items()[0].name();
console.log(item1Name);
},1500);
View :
<table>
<tbody data-bind="foreach : items">
<tr>
<td data-bind="text : name"></td>
</tr>
</tbody>
</table>
<span data-bind="visible : items().length == 0">Loading...</span>
See fiddle
I hope it helps.
回答2:
You need to call ko.applyBinding in the callback of the ajax to make sure the data is available. Currently this is happening before then at the top. This is your issue. If you want further help, I suggest you create a fiddle of your problem and let me and others try to fix it for you.
来源:https://stackoverflow.com/questions/17422552/knockout-js-binding-and-ajax-taking-longer-to-load