Nicolas Pierre
Nicolas Pierre

Reputation: 1195

Async getJSON with knockout.JS

I'm trying to call a JSON result in my HTML with Knockout.JS with following code.

$(document).ready(function () {
var submissionViewModel = new SubmissionModel();
submissionViewModel.getSubmission().done(function () {
    ko.applyBindings(submissionViewModel, document.getElementById("submission"));
  })
});

var SubmissionModel = function () {
var self = this;
self.Submission = ko.observable(null);

self.getSubmission = function () {

    $.getJSON('/Submission/GetSubmission',
        function (data) {
            self.Submission = ko.mapping.fromJSON(JSON.stringify(data));
        }
    );
  }
}

For starters I'm fairly new with the Knockout JS lib so bear with me. From what I can get is that my applybindings is happening before my JSON is loaded into the Submission property.

I tried putting the thread to bed and started rocking the cradle but that resulted in following error

Uncaught TypeError: Unable to process binding text: function (){return (). } Message: Cannot read property of null

I get what's happening and that I need to halt the execution of the $(document).ready code untill the JSON call is completed. I tried to achieve this with the .done function in jQuery but that resulted in the following error

Cannot read property 'done' of undefined

As I am not that experienced in knockout could any of you guys point me in the right direction ?

Upvotes: 2

Views: 451

Answers (1)

Dandy
Dandy

Reputation: 2177

You code seems fine. In your self.getSubmission function, return the promise object like

self.getSubmission = function () {

    return $.getJSON('/Submission/GetSubmission',
        function (data) {
            self.Submission(ko.mapping.fromJSON(JSON.stringify(data)));
        }
    );
  }

'done' is undefined because you are not chaining it with javascript promise object.

Upvotes: 2

Related Questions