我试图从我的服务器获取一些数据,从这些数据创建对象,然后在我的页面上以 foreach 数据绑定显示它。
这是我的代码:
self.houses = ko.observableArray([]);
self.flats = ko.observableArray([]);
function Building(item, checked){
self = this;
self.id = item.id;
self.name = item.nazwa;
self.photo = '/' + item.pic;
self.type = item.type_text;
self.selected = ko.observable(checked);
}
$.getJSON("/api/getHouses", function(allData) {
self.houses($.map(allData, function(item) { return new Building(item, 0) }));
});
$.getJSON("/api/getFlats", function(allData) {
self.flats($.map(allData, function(item) { return new Building(item, 0) }));
});
当我运行此代码时,出现错误:
self.flats is not a function
如果我要删除 getJSON 函数之一,并且只有一个(其中一个),则它可以正常工作。我可以一次只有一个 observableArray 吗?
看起来问题在于“self”变量正在被 Building 函数改变,并且在 ajax 调用返回时不再指向根视图模型。修复可能就像在前面放置“var”一样简单self = this
self.houses = ko.observableArray([]);
self.flats = ko.observableArray([]);
function Building(item, checked){
//self = this;
var self = this; //the fix
self.id = item.id;
self.name = item.nazwa;
self.photo = '/' + item.pic;
self.type = item.type_text;
self.selected = ko.observable(checked);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句