I am trying to read an xml file and then display the contents of it in a table, I have got it almost working but something is amiss with the timing of the processes ( it seems reading the xml will take place later then the binding ).
Any help will be much appreciated. The xml I want to read can be downloaded here.
html code:
<!DOCTYPE html>
<table id="table2" summary="Album List" aria-label="Album Table"
data-bind="ojComponent: {component: 'ojTable',
data: datasource,
columnsDefault: {sortable: 'none'},
columns: [{headerText: 'Id',
field: 'id'},
{headerText: 'Artist',
field: 'artist'},
{headerText: 'Title',
field: 'title'}]}">
</table>
javascript code:
deptArray = new Array();
require(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout', 'promise', 'ojs/ojtable'],
function(oj, ko, $)
{
function viewModel()
{
loadXMLDoc();
alert('test:'+deptArray.length);
var self = this;
//deptArray = [{id: 1, artist: "a", title: "b"}];
//deptArray.push({id: 2, artist: "c", title: "d"});
//alert('test:'+deptArray[0].artist);
self.datasource = new oj.ArrayTableDataSource(deptArray, {idAttribute: 'id'});
}
var vm = new viewModel;
$(document).ready
(
function()
{
alert('start');
ko.cleanNode($('#table2')[0]);
ko.applyBindings(vm, document.getElementById('table2'));
alert('end');
}
);
});
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
alert('loadxmldoc:'+deptArray.length);
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var l_artist;
var l_title;
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
l_artist = x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
l_title = x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
if ( i === 0 ) {
deptArray = [{id: i, artist: l_artist, title: l_title}];
} else {
deptArray.push({id: i, artist: l_artist, title: l_title});
}
}
alert('myFunction:'+deptArray.length);
}