gpt4 book ai didi

javascript - Knockout.js 绑定(bind)未更新

转载 作者:行者123 更新时间:2023-12-03 05:53:59 25 4
gpt4 key购买 nike

我正在尝试从 API 检索数据后填充表。

相关 HTML:

<tbody data-bind="foreach: places">
<tr>
<td data-bind="text: clientName"></td>
<td data-bind="text: name"></td>
<td data-bind="text: address1"></td>
<td data-bind="text: address2"></td>
<td data-bind="text: city"></td>
<td data-bind="text: county"></td>
<td data-bind="text: country"></td>
<td data-bind="text: dateAdded"></td>
</tr>
</tbody>

js:

function Place(data) {
this.clientName = ko.observable(data.ClientName);
this.name = ko.observable(data.Name);
this.address1 = ko.observable(data.Address1);
this.address2 = ko.observable(data.Address2);
this.city = ko.observable(data.City);
this.county = ko.observable(data.County);
this.country = ko.observable(data.Country);
this.dateAdded = ko.observable(data.DateAdded);
}

function PlaceListViewModel() {
var self = this;
self.places = ko.observableArray([]);

$.ajax({
type: "POST",
url: "SubscriberDashboard/SearchPlaces",
contentType: "application/json",
data: { "SearchTerm": "" },
success: function (data) {
var temp = [];
$.each(data.places, function (placeData) {
temp.push(new Place(placeData));
});
self.places(temp);
console.log(self.places());
}
});

}

ko.applyBindings(new PlaceListViewModel());

数据加载正常,ajax 调用末尾的 console.log 显示 Place 对象数组。同样,适当的数量<tr>元素已渲染,但 <td> 中没有文本元素。

编辑:

function PlaceListViewModel() {
var self = this;
self.places = ko.observableArray([]);

$.ajax({
type: "POST",
url: "SubscriberDashboard/SearchPlaces",
contentType: "application/json",
data: { "SearchTerm": "" },
success: function (data) {
$.each(data.places, function (placeData) {
self.places.push(new Place(placeData));
});
console.log(self.places());
}
});

}

最佳答案

您正在将索引传递给地点模型而不是实际数据。 $.each function 的第一个参数是 index,第二个参数是 element

$.each() 函数(整数索引,Element元素)。

此外,最好为每个必须避免冲突的子模型使用 var self = this

示例:https://jsfiddle.net/kyr6w2x3/94/

$.each(data, function (index , placeData) {
self.places.push(new Place(placeData));
});

关于javascript - Knockout.js 绑定(bind)未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40021589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com