2

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!

jamesplease
  • 12,547
  • 6
  • 47
  • 73

2 Answers2

2

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?

Community
  • 1
  • 1
Geoff
  • 9,340
  • 7
  • 38
  • 48
  • Good suggestion. I had tried this as well, but when I do it it displays a length of `0`. – jamesplease Dec 18 '12 at 17:23
  • your viewModel.length will always be 0 since viewModel is a function. this question can help with debugging bindings: http://stackoverflow.com/questions/9261296/any-good-techniques-to-debug-template-binding-faults-for-knockout-js – Geoff Dec 18 '12 at 17:25
  • +1 for the good link reference. You should put that in your answer – jamesplease Dec 18 '12 at 17:44
2

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)

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55