knockout mapping JSON update existing view model

jquery, knockout-mapping-plugin, knockout.js

Solution

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.

Problem

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.

Original source