I'm using Knockout to bind an MVC view. This works fine the first time but for subsequent refreshes Knockout throws the error:
Error: You cannot apply bindings multiple times to the same element.
This is my binding code (inside Document.Ready), note that I am using setTimeout to run every 25 seconds, this is where the error occurs:
function viewModel() {
Loading = ko.observable(true),
CurrentUser = ko.observable(),
Environments = ko.observableArray(),
CurrentFormattedDate = ko.observable()
}
function doPoll() {
$.get("/home/getindex")
.done(function (data) {
$(data).each(function (index, element) {
viewModel = data;
viewModel.Loading = false;
viewModel.CurrentFormattedDate = moment().format('MMMM YYYY');
});
ko.applyBindings(viewModel);
})
.always(function () {
setTimeout(doPoll, 25000);
})
.error(function (ex) {
alert("Error");
});
};
doPoll();
How do I avoid the error when DoPoll is called multiple times?
$(data).each? You seem to never utilize theindex/elementarguments and just update the same object in a loop. The result would be equivalent to not using a loop at all. Also, I theviewModelobject is wrong. You need to putthisinside the member initialization, likethis.Loading = ..., otherwise the supposed members will become global variables, and that is bad practice in JS!. - Ivaylo Slavov