Question

This is my first time using the Knockout Mapping plugin to create my viewmodel directly from JSON from the server. The initial set of data comes from the server, then I poll for changes ever 10 seconds. This code works, but I feel like it is not very DRY.

I've looked all over for better examples but haven't had any luck. How can I avoid calling getJSON in two different places?

In my customer-scripts.js file:

function CustomerRefresher(id) {
    var viewModel;

    $.getJSON('/ApiCustomer/Get/' + id, function (data) {
        viewModel = ko.mapping.fromJS(data);
        ko.applyBindings(viewModel);
        setTimeout(refresh, 10000);
    });

    var refresh = function () {
        $.getJSON('/ApiCustomer/Get/' + id, function (data) {
            ko.mapping.fromJS(data, {}, viewModel);
        });

        setTimeout(refresh, 10000);
    }
}

In my .cshtml file:

$(function () {
    CustomerRefresher(@Model.Id);
});
Was it helpful?

Solution

function CustomerRefresher(id){
  var refresh = function(){
    $.getJSON('/ApiCustomer/Get/' + encodeURIComponent(id), function(data){
      if (typeof CustomerRefresher.viewModel !== 'undefined'){
        ko.mapping.fromJS(data, {}, CustomerRefresher.viewModel);
      }else{
        CustomerRefresher.viewModel = ko.mapping.fromJS(data);
        ko.applyBindings(CustomerRefresher.viewModel);
      }
      setTimeout(refresh, 10000);
    });
  };
  refresh();
}

Something like that? (can use the function itself to "cache" the view model) Also, example provided.

Also, FWIW, this is probably better suited for codereview.SE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top