Search code examples
javascriptknockout.jsknockout-mapping-plugin

KnockoutJS Nested Mapping


I'm using KnockoutJS, and the mapping plugin, to create a user interface. When the page loads, it immediately calls:

$('document').ready ( function () {
  $.getJSON(some-url, function (data) {
    viewModel = new ViewModel(data);
    ko.applyBindings(viewModel);
  });
});

That works great. The service at some-url responds with a JSON value of the form:

{ current: null
, ids: [0,1,2,3,4,5]
}

And I have created a method in my ViewModel class which is supposed to populate the current observable, based on the first id in the array:

self.head = function () {
  if (self.promptIds().length != 0) {
    var nextId = _.head(self.promptIds());
    self.promptIds(_.tail(self.promptIds()));
    $.getJSON("some-url" + "/" + nextId, function (data) {
      self.current = ko.mapping.fromJS(data);
    });
  }
}

Notice that I am setting self.current to be equal to the result of doing ko.mapping. So I am pretty much overwriting the previous observable there. And that explains why my bindings aren't updating, even though self.current is defined.

So how do I go about updating just the viewModel.current observable? All I want is to parse the response of an ajax query and make it a sub-viewModel.


Solution

  • I thought its:

    self.current(ko.mapping.fromJS(data));