Search code examples
javascriptknockout.jsko.observablearray

Add data to end of ko.observablearray


I'm trying to add data to the end of an observable array but it's just not working as expected. I bet it is something minor but I just can't get my head around it.

What I am doing:

      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);

This all works as expected and the obersablearray is populated.

However if I go to add another business, it wont work. For example, if I call the ajax that returns this (as newBusiness):

{
    "$id": "1",
    "BusinessID ": 68,
    "Type": "Data",
    "Location": "Data"
}

and I do:

self.businesses().push(newBusiness);

It adds to the array as an "Object" not a Business. So I thought I would do:

var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);

But I get the error in the JS console "Uncaught TypeError: Cannot read property 'BusinessID' of null

So I made a new var and added the brackets: [] in and it adds to the observable array but not as a "Business" object but rather as an "Array[1]" object at the end and this doesn't function as per the others. Code as follows:

    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);

As mentioned this adds to the observable array but doesn't actually add as a "business" object but rather as an "array[1]" object.

I bet it's something so basic but just can't get it working!


Solution

  • Argh I knew it would be simple!

    It was posting the whole array to the ObservableArray...not just the object.

    The fix:

    self.businesses.push(newBusiness[0])
    

    Had to add the [0] in to get it to push the actual data into the array, not the object!

    Thanks for the answers!