ledgeJumper
ledgeJumper

Reputation: 3630

After performing $.getJSON how can I put the resulting data into my knockout observables?

I always get a little lost whenever I am doing something more than basic javascript. I have a knockout viewmodel like so:

function UserSettingsViewModel(apiBaseUrl, userId) {
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();

self.fullName = ko.computed(function () {
    return self.firstName() + " " + self.lastName();
}, this);

var vmData = $.getJSON(apiBaseUrl + "?userId=" + userId, function (data) {
    alert(JSON.stringify(data));
});

self.firstName(vmData.FirstName);
}

I am following along on the tutorial on knockouts site. This will expand into something that will hold first and last name, two email addresses, an address model, and more. I guess asking how to properly do that is another question. Baby steps.

I am getting the right result from the getJSON call, something like this:

{
    "FirstName":"Test Data",
    "LastName":"Test Data",
    ...more stuff...
}

How can I put all this data into my knockout observables when the data comes in so it updates my page automagically?

I know there is a plugin for mapping. If I ought to go that route, can you possibly show me an example or point me to a good tutorial? The end product of this page is going to be a object like this (C# Model Class):

public class UserSettingsViewModel
{
    public string UserGuid { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PrimaryEmail { get; set; }
    public string SecondaryEmail { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
}

This is the object getting passed back from the webapi get method.

Upvotes: 0

Views: 74

Answers (1)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

I don't know about ko, but I hope one of these 2 options works for you:

Option 1:

$.getJSON(apiBaseUrl + "?userId=" + userId, function (data) {    
    self.firstName(data.FirstName);
});

Option 2: Synchronous (not recommended, use as last resource):

$.ajaxSetup({async: false});
$.getJSON(apiBaseUrl + "?userId=" + userId, function (data) {    
    self.firstName(data.FirstName);
});
$.ajaxSetup({async: true});

The second one is not recommended because as the call is async, execution will stop until the ajax call finishes.

Cheers

Upvotes: 1

Related Questions