I have been working on a project that uses knockout for databinding from javascript to html. I am also reading data from a PLC using ajax, the data from the ajax request will put into the knockout viewmodel and shown on the webpage. I am having some trouble with the updating of the data binding. I searched on the internet for help but didn't find anything so far that helped me so I hope you can help me further.
I have setup the viewmodel as following inside a javascript file:
function AppViewModel() {
var self = this;
self.hmitags = ko.observableArray(groupDataValues);
self.Capa100 = ko.observable("Cap100");
self.Testvar = ko.observable(50);
}
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
And have the data binding in the html file: <span data-bind="text: Testvar></span>
when I now load the html file I see the value 50 as defiened in the viewmodel, so that is working. But now I want to read a variable from my PLC using ajax that is done through a function inside that same javascript file. This is how the function looks:
function ReadVariable()// function for reading out individual variables
{
// list can contain only one variable
var HMIReadList = "&paths=MainInstance.Testvar"
data.length = 0; // get rid of the data from the last query
// issue the data request
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + BearerToken);
}
});
$.ajax({
type: "GET",
url: baseurl + "_pxc_api/api/variables?pathPrefix=Arp.Plc.Eclr/" + HMIReadList,
})
.done(function (data, status, jqXHR) {
viewModel.Testvar = data.variables[0].value;
console.log(viewModel.Testvar);
})
.fail(function (jqXHR, status, errorThrown) {
console.log("CreateSession Error: " + errorThrown);
console.log("Status: " + status);
console.dir(jqXHR);
alert("CreateSession $.ajax failed. Status: " + status);
});;
}
I am using a button in the html page to call this function. In the console I can see that it is reading a value from the PLC and that it is different that the initial value 50. But on the html page it is not changing. I am not sure why it isn't working I have been looking around for some solutions but have not found anything that is working.
A knockout observable is a function. In order to update the value of the observable, you need to invoke the function with the new value as follows: viewModel.Testvar(data.variables[0].value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.