LemmyLogic
LemmyLogic

Reputation: 1083

Load Knockout observableArray not working

Trying to load an observableArray with json from server like this:

function InsightViewModel() {
    var self = this;
    self.Name = ko.observable("");

    var insightData = {
        Name: self.Name
    };

    self.insightData = ko.observable();
    self.Insights = ko.observableArray([]);

    $.ajax({
        type: "GET",
        url: '@Url.Action("GetIndexData", "Admin")',
        contentType: "application/json",
        dataType: "json",
        data:{},
        success: function (data) {
            self.Insights(data);
            alert(JSON.stringify(data) + "Array length " + self.Insights.length);
        },
        error: function (error) {
            alert(error.status + " " + error.statusText);
        }
    });
};

var viewModel = new InsightViewModel();
ko.applyBindings(viewModel);
alert(viewModel.Insights.length);

I can alert out the json from the server, and it is valid. But the array is empty.

I tried this, with no luck:

$(data).each(function (element) {
   self.Insights.push(element);
});

Not that experienced with knockout. Any thoughts?

Upvotes: 0

Views: 277

Answers (2)

Ramppy Dumppy
Ramppy Dumppy

Reputation: 2817

The reason why the array is empty because by default ajax is asyncronous. the work around is to add async: false in your ajax call, but that is not the best practic. Instead of adding async : false use .done...

function InsightViewModel() {
     var self = this;
     self.Name = ko.observable("");

    var insightData = {
        Name: self.Name
    };

    self.insightData = ko.observable();
    self.Insights = ko.observableArray([]);

    $.ajax({
        type: "GET",
        url: '@Url.Action("GetIndexData", "Admin")',
        contentType: "application/json",
        dataType: "json"            
    })
    .done(function(data)
    {
        self.Insights(data);
    });
 };

var viewModel = new InsightViewModel();
ko.applyBindings(viewModel);
alert(viewModel.Insights.length());

Hope this work...

Upvotes: 0

alexmac
alexmac

Reputation: 19597

You are incorrectly get length Insights observableArray, it should be like this:

self.Insights().length // with brackets

Another problem, as described @haim770 is calling alert after ko.applyBindings(viewModel). There is a big chance, that ajax request is not completed yet.

Upvotes: 1

Related Questions