Reputation: 13818
In Brief : I need to replace an entire object inside my viewmodel which is created through the knockout mapping plugin. How do I do this? This should in-turn update the controls bound to that object...
More details :
I am using knockout with signalR.
I'm able to retrieve the JSON from the server during page load,parse it using ko.mapping.FromJSON or FromJS after using ParseJSON and it loads it into the viewmodel during the first time.
But, after that, I am unable to update the viewmodel from the server using SignalR.
Here's my viewmodel :
function viewmodel(objServerModel) {
var self = this;
self.profile = objServerModel;
self.devices = ko.observableArray(['one', 'two']);
self.updateprofile = ko.observable('@Html.Raw(HttpUtility.JavaScriptStringEncode(Test.ReadXmlIntoModel()))')
}
Here's the code I am using to update the model during run time..the following function is called from the server...
function UpdateVM(modeljson)
{
var objResult = $.parseJSON(modeljson);
var objModelFromServer = ko.mapping.fromJS(objResult, {},objModel.profile);
// var objFinal = objResult.capture.capturevideo.videodevice.Value;
// objModel = viewmodel(objModelFromServer);
// objModel.profile(objModelFromServer);
viewmodel(objModelFromServer);
return objModel;
}
This textbox should get updated during run time when UpdateVM is called :
<input id="txt1" data-bind="value: profile.capture.capturevideo.videodevice.Value" type="text" />
Please help...
Thanks.
Edit : Please note that it's not a string. It's an object created using knockout's mapping plugin.I need to replace the existing object with another object of the same structure with different values created by the mapping plugin
Upvotes: 0
Views: 1819
Reputation: 1232
The property you are trying to update is not an observable property, so updating it will not update the UI. I'm not sure what your profile object looks like but it needs to have some observable properties in it. For example :
function viewmodel()
{
var self = this;
self.profile = new profile();
}
function profile() {
var self = this;
self.foobar = ko.observable(1);
self.barfoo = ko.observable("hello");
}
Now in your UpdateVM()
function you would need to just update the properties of the profile object.
function UpdateVM(modeljson)
{
var objResult = $.parseJSON(modeljson);
viewmodel.profile.foobar(objResult.foobar);
viewmodel.profile.barfoo(objResult.barfoo);
}
This should cause your UI to update.
Upvotes: 1