I have this JSON data coming from the server:
{"HaveNotification":false,"IsError":false,"Title":null,"Description":null}
and am trying to populate this view model via ko.mapping:
var notifyVM = {
HaveNotification: ko.observable(true),
IsError: ko.observable(false),
Title: ko.observable('Title goes here'),
Description: ko.observable('Description goes here'),
}
with this code, which is called on a polling interval:
function pollNotifications() {
$.getJSON('@Url.Action("GetNotifications", "Home")', function (data) {
ko.mapping.fromJSON(data, notifyVM);
setTimeout(pollNotifications, 10000);
});
}
and this is page load code:
$(function () {
ko.applyBindings(notifyVM);
setTimeout(pollNotifications, 10000);
});
but its not working. If I inspect the view model after the fromJSON call the observables are not updated, they are still at their initial values.
UPDATE: Some more info... if I do this in the pollNotifications function
var newVM = ko.mapping.fromJSON(data);
I notice that the view model it creates is not the same as my one, it consists of a single observable function, whereas mine is an object with a set of observable properties.
Try:
ko.mapping.fromJS(data, {}, notifyVM);
The two parameter form expects a view-model that was previously created with ko.mapping.fromJS. If it doesn't find one (based on looking for a specific property that fromJS adds), it assumes you're calling the fromJS(data, options) form.
The 3 parameter form removes this ambiguity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With