jamesplease
jamesplease

Reputation: 12879

Knockout JS Mapping from JSON not working

I'm receiving a JSON string and attempting to map it to a KOJS VM, but I don't see why the below code isn't working.

Here's my JS file:

var viewModel = {};

$.ajax({
  url: '../data/settings',
  cache: false,
  success: function(data) {
    alert(data);
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
  }
});

The first alert displays:

{"remember":"false"}

My HTML, which isn't working is:

<span data-bind="value:remember"></span>

Do you know what might be going wrong here? Thanks!

Upvotes: 2

Views: 3006

Answers (2)

Geoff
Geoff

Reputation: 9340

It looks like your data might not be a JSON string so you want to use fromJS instead:

viewModel = ko.mapping.fromJS(data);

This question can help with debugging bindings: How to debug template binding errors for KnockoutJS?

Upvotes: 2

Kevin Boucher
Kevin Boucher

Reputation: 16705

I think the problem may be your binding code:

<span data-bind="value:remember"></span>

should be:

<span data-bind="text:remember"></span>

See this fiddle: http://jsfiddle.net/kboucher/Jj9DZ/

'value' is for form fields that have a value property (and may be abstracted to include select boxes as well)

Upvotes: 2

Related Questions