'Knockout Binding not happen correctly
I want to bind data by knockout but data not binding correctly I have gotten the data by ajax and put it in self.DisplayItem object successfully But the problem in Binding only where data not shown in the div
This is javascript code:
function CustomItem(prams) {
var self = this;
self.Id = ko.observable(prams.Id || 0);
self.Name = ko.observable(prams.Name || "");
self.Title = ko.observable(prams.Title || "");
}
function BaseViewModel() {
var self = this;
self.DisplayItem = ko.observable(null);
self.DisplayItem = new CustomItem({
Id: 0,
Name : "",
Title : ""
});
self.GetDetails = function (Id) {
$.ajax({
type: "POST",
url: URL + 'Customer/GetDetails/' + Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.DisplayItem = new CustomItem(data);
},
});
};
ko.applyBindings(self);
}
Html code:
<button data-bind="click: $root.GetDetails">Show Data</button>
<div class="row">
<div class="col-lg-2">
<div><label class="control-label">Name</label></div>
<div data-bind="text: DisplayItem.Name"></div>
</div>
<div class="col-lg-2">
<div><label class="control-label">Title</label></div>
<div data-bind="text: DisplayItem.Title"></div>
</div>
</div>
Solution 1:[1]
You are overwriting the observable functionality by assigning to the observable property.
Instead, pass the assigned value to the function
that the observable property becomes:
self.DisplayItem(new CustomItem({
Id: 0,
Name : "",
Title : ""
}));
and when you have fetched your data:
self.DisplayItem(new CustomItem(data));
For reference, see reading and writing observables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | connexo |