将数据添加到 ko.observablearray 的末尾

Add data to end of ko.observablearray

我正在尝试将数据添加到可观察数组的末尾,但它没有按预期工作。我敢打赌这是小事,但我无法理解它。

我在做什么:

      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 称为 returns 这个(作为新业务):

{
    "$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 控制台中收到错误“未捕获的类型错误:无法读取 属性 'BusinessID' of null

所以我创建了一个新的 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]" 对象添加。

我敢打赌这是非常基础的东西,但就是无法正常工作!

您正在通过推送评估数组:

self.businesses().push(newBusiness);

Observable Arrays 有自己的数组函数,你应该这样做(没有括号):

self.businesses.push(newBusiness);

查看此页面:http://knockoutjs.com/documentation/observableArrays.html

啊我知道这会很简单!

它将整个数组发布到 ObservableArray...而不仅仅是对象。

修复:

self.businesses.push(newBusiness[0])

必须添加 [0] 才能将实际数据推入数组,而不是对象!

感谢您的回答!