nomen
nomen

Reputation: 3725

Pager.js: How to lazy load bindings

I am trying to figure out how to use Pager.js in conjunction with Knockout.js to lazy-load a page and bind its contents. I am trying to translate the demo example, but I am not familiar with require.js and am just getting lost.

I have spent several hours trying to reimplement the system using jQuery's getJSON instead of require and define, but the bindings are failing silently. I am having two issues:

  1. The view model is a JSON array, so I don't know what the array is called
  2. The code is not actually doing a getJSON request (nothing in the logs). And is failing silently.

Here is the code:

<div data-bind="page: {id: 'history', title: 'History', withOnShow: $root.getHistory }">

var ViewModel = function (data) {
  var self = this;
  ko.mapping.fromJS(data, {}, self);

  self.getHistory = function () {
    return function (f) {
      $.getJSON("@{HistoryR}", function (data) {
        viewModel.history = ko.mapping.fromJS(data, {});
        f(viewModel.history);
      });
    }
  }          
};

$.getJSON("@{HomeR}", function (data) {
  viewModel = new ViewModel(data);
  pager.extendWithPage(viewModel);
  ko.applyBindings(viewModel);
  pager.start();
});

I refactored the code some, to fit in with huocp's answer:

  self.getExamHistory = function (f) {
    $.getJSON("@{ExamHistoryR}", function (data) {
      self.history = ko.mapping.fromJSON(data, {});
      f(self.history);
    });
  }

and the getJSON call is getting triggered (and I see the response in my console), but my viewModel.history is still empty.

Upvotes: 0

Views: 1092

Answers (1)

user1375096
user1375096

Reputation:

You did a wrong wrap of withOnShow callback function.

Remove the wrap, you should be fine :-)

self.getHistory = function (f) {
  $.getJSON("@{HistoryR}", function (data) {
    self.history = ko.mapping.fromJS(data); // can u try self instead of viewModel
    f(self.history);
  });
};

The reason the Pager.js demo page with extra wrap, is that it use withOnShow: requireVM('invention'), not withOnShow: requireVM. It uses the return value of requireVM function, not the function itself.

Upvotes: 1

Related Questions