我试图将数据添加到可观察数组的末尾,但它只是没有按预期工作。我打赌这是次要的,但我无法理解它。
我在做什么:
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);
它将数组添加为" Object"不是生意。所以我想我会这样做:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
但是我在JS控制台中得到了错误" Uncaught TypeError:无法读取属性' BusinessID'为null
所以我创建了一个新的var并添加了括号:[] in并且它添加到了可观察数组但不是" Business"对象,而是作为"数组[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);
如上所述,这增加了可观察数组,但实际上并未添加为"业务"对象,而是作为一个"数组[1]"对象
我敢打赌这是一个非常基本的东西,但却无法让它发挥作用!
答案 0 :(得分:3)
唉,我知道这很简单!
它将整个数组发布到ObservableArray ...而不仅仅是对象。
修复:
self.businesses.push(newBusiness[0])
必须添加[0]才能将实际数据推送到数组中,而不是对象!
感谢您的回答!
答案 1 :(得分:0)
您正在使用推送评估数组:
self.businesses().push(newBusiness);
Observable Arrays有自己的数组函数,你应该这样做(没有parens):
self.businesses.push(newBusiness);
请参阅此页:http://knockoutjs.com/documentation/observableArrays.html