我从web api获取数据并将数据推送到可观察数组中。我想使可观察的数组项可观察。但是,如果我让它可观察,我似乎无法访问该对象。
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function() {
$.ajax({
type: 'GET',
success: function() {
$.each(data.ProfileList, function (index, value) {
self.ProfileList.push(value);
alert(self.ProfileList()[index].Name) // success
}
}
});
}
self.GetProfile();
}
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function() {
$.ajax({
type: 'GET',
success: function() {
$.each(data.ProfileList, function (index, value) {
self.ProfileList.push(ko.observable(value));
alert(self.ProfileList()[index].Name) // fail. Object does not support property or method 'Name'
}
}
});
}
self.GetProfile();
}

答案 0 :(得分:3)
你是直接推动object
(通过使其可观察)进入observableArray听起来是否合适?不(你可能想让Name
成为可观察到的,我相信)。通过这样做self.ProfileList()[index]().Name
检查 here
首选方式:
<强>视图模型:强>
function convert(data) {
this.Name = ko.observable(data.Name)
this.place = ko.observable(data.place)
this.age = ko.observable(data.age)
}
function KnockoutViewModel() {
var self = this;
self.ProfileList = ko.observableArray([]);
self.GetProfile = function () {
var data = [{
'Name': 'Super',
'place': 'Ind',
'age': 25
}, {
'Name': 'Cool',
'place': 'Aus',
'age': 15
}]
//Manual way with function defined
//self.ProfileList(ko.utils.arrayMap(data, function (value) {
// return new convert(value)
//}))
//Using Mapping Plugin
ko.mapping.fromJS(data,{},self.ProfileList)
}
self.GetProfile();
}
ko.applyBindings(new KnockoutViewModel());
工作样本 here
答案 1 :(得分:1)
尝试使用映射模块:
self.ProfileList.push(ko.mapping.fromJS(value));
这将自动将值的属性包装在knockout observables中。