将数据添加到 ko.observablearray 的末尾
2015-01-29
754
我试图将数据添加到可观察数组的末尾,但它没有按预期工作。我敢打赌这是一件小事,但我就是无法理解。
我正在做什么:
self.businesses = ko.observableArray();
function Business(business) {
var self = this;
self.BusinessID = ko.observable(business.BusinessID );
self.Type = ko.observable(business.Type);
self.Location = ko.observable(business.Location);
}
/*ajax get array of businesses as follows:
[
{
"$id": "1",
"BusinessID ": 62,
"Type": "Data",
"Location": "Data"
},
{
"$id": "2",
"BusinessID ": 63,
"Type": "Data",
"Location": "Data"
},
{
"$id": "3",
"BusinessID ": 64,
"Type": "Data",
"Location": "Data",
} ]
*/
var mappedBusinesses = $.map(data, function (business) { return new Business(business) });
self.businesses(mappedBusinesses);
这一切都按预期工作,并且 obersablearray 已填充。
但是,如果我要添加另一个业务,它将不起作用。例如,如果我调用返回此内容的 ajax(作为 newBusiness):
{
"$id": "1",
"BusinessID ": 68,
"Type": "Data",
"Location": "Data"
}
然后我这样做:
self.businesses().push(newBusiness);
它将作为“对象”而不是业务添加到数组中。所以我想我会这样做:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
但是我在 JS 控制台中收到错误“未捕获的 TypeError:无法读取 null 的属性‘BusinessID’
所以我创建了一个新的 var 并添加了括号:[] 并将其添加到可观察数组中,但不是作为“Business”对象,而是作为末尾的“Array[1]”对象,并且这不能像其他对象那样运行。代码如下:
var newBus = {
BusinessID: newBusiness.BusinessID,
Type: newBusiness.Type,
Location: newBusiness.Location
}
var bus = $.map(newBus, function (business) { return new Business(business) });
self.businesses().push(bus);
如上所述,这会添加到可观察数组中,但实际上并没有添加为“business”对象,而是添加为“array[1]”对象。
我敢打赌这是非常基本的东西,但就是无法让它工作!
2个回答
啊,我知道这很简单!
它将整个数组发布到 ObservableArray...而不仅仅是对象。
修复:
self.businesses.push(newBusiness[0])
必须添加 [0] 才能将实际数据推送到数组中,而不是对象中!
谢谢您的解答!
user3129594
2015-01-30
您正在使用推送来评估数组:
self.businesses().push(newBusiness);
可观察数组有自己的数组函数,您只需执行以下操作(无括号):
self.businesses.push(newBusiness);
请参阅此页面: http://knockoutjs.com/documentation/observableArrays.html
dfperry
2015-01-29