Tom Riley
Tom Riley

Reputation: 1722

Knockout: Mapping/binding JSON issue

i'm trying a basic hello work example getting json, auto mapping it and then binding to an observable, I'm sure i'm getting something basic wrong.

JSON returned from ajax call

"{\"Content\":\"hello world\"}"

JS

function ViewModel() {
var self = this;

self.message = ko.observable();

$.getJSON("/home/getmessage", function (response) {
    var mapped = ko.mapping.fromJSON(response);
    self.message(mapped.Content);
});
};

ko.applyBindings(new ViewModel());

I'm getting the following in place of 'hello world' that i was expecting

function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}

Upvotes: 2

Views: 1220

Answers (1)

Tom Riley
Tom Riley

Reputation: 1722

Sorted, I had overlooked the fact ko.mapping returns observables so you have to call them as a function to get their value.

function viewModel() {
var self = this;

self.content = ko.observable();

$.getJSON("/home/getmessage", function (response) {
    var mapped = ko.mapping.fromJSON(response);
    self.content(mapped.Content());
});
}

ko.applyBindings(new viewModel);

Upvotes: 1

Related Questions