Reputation: 1
I have the following knockout's viewModel :
var viewModel={ businessName: "", .... }
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "@Html.Raw(@Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result: if I use Option1, I get the new data but it does not get updated on the page. If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page? I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
Upvotes: 0
Views: 89
Reputation: 10153
You have to use ko.observable
in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName
. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.
Upvotes: 0
Reputation: 45135
ko.observable
is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind
syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
Upvotes: 0