0

I have a <select> that is populated with a list from the database. I use a jquery ajax call to get the data. At first I was setting async = false so the call is synchronous and I update my VM once the call is done. I'm trying to get away from doing synchronous calls by using promises and I ran into an issue. (To simplify this example I have removed promises.)

I thought I could create a function that would make the call to ajax and return an observable. Then once the ajax call finishes, the observable would be updated and new values would be seen in the <select>. The problem I have is if I use a normal function, it behaves like a recursive call and the observable is updated over and over. If I use a computed observable this doesn't happen. The reason I'd like to use a function instead of a computed is so I can pass other arguments in. (My understanding is you can't pass arguments to an observable)

At this point, I think my best option is to use a computed and try and figure out a different way to get the arguments, but I'd like to understand why using a plain function doesn't work.

I have created a plunk to show this: (On the select element change getAvailableCountries() to getAvailableCountries2() to see the difference) http://plnkr.co/v1Q0bBhWOAHQSv8N1vwu

HTML:

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css" />

  <script data-require="jquery@*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.js"></script>
  <script data-require="knockout@*" data-semver="3.2.0" src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

  <script src="mockJax.js"></script>
  <script src="script.js"></script>
</head>

<body>
  <section>
    <label class="control-label">Your country:</label>
      <select class="form-control" data-bind="options: getAvailableCountries(),
                       optionsText: 'countryName',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'"></select>
    <div data-bind="visible: selectedCountry">
      <hr>
      <label class="control-label">You have chosen a country with population:</label>
        <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>
      <hr>
    </div>
  </section>
  <br>
  <footer>
    <label>ko.toJSON():</label><br>
    <span data-bind="text: ko.toJSON($data, null, 2)"></span>
  </footer>
</body>
</html>

JS:

var Country = function(name, population) {
  this.countryName = name;
  this.countryPopulation = population;
};

var viewModel = function() {
  var availableCountries = ko.observableArray([new Country("First Country", 5000)]);
  var selectedCountry = ko.observable();

  function callAjax() {
    $.mockjax({
      url: '/Countries',
      responseTime: 2000,
      responseText: [{
        population: 1000,
        name: "Country A"
      }, {
        population: 2000,
        name: "Country B"
      }, {
        population: 3000,
        name: "Country C"
      }]
    });
    $.ajax({
      dataType: "json",
      url: "/Countries",
      success: function(data, status, jqXhr) {
        for (i = 0; i < data.length; i++) {
          var tmpData = data[i];
          var tmpCountry = new Country(tmpData.name, tmpData.population);
          availableCountries.push(tmpCountry);
        }
      },
    });
  }

  var getAvailableCountries = ko.computed(function() {
    callAjax();
    return availableCountries;
  });

  var getAvailableCountries2 = function() {
    callAjax();
    return availableCountries;
  };

  var testAjax = function() {
    $.ajax({
      dataType: "json",
      url: "/Countries",
      success: function(data, status, jqXhr) {
        var x = 1;
      }
    });
  };

  return {
    availableCountries: availableCountries,
    selectedCountry: selectedCountry,
    getAvailableCountries: getAvailableCountries,
    getAvailableCountries2: getAvailableCountries2,
    testAjax: testAjax,
  };
};

$(document).ready(function() {
  ko.applyBindings(viewModel);
});

Here's the plunk after reviewing the accepted answer: http://plnkr.co/edit/LvFWVG3pDrVbvPvLm7Cu

2
  • Why don't you just bind directly to availableCountries in options: availableCountries and then you call viewModel.callAjax() after the ko.applyBindings(viewModel); or whenever you need to update the availableCountries? plnkr.co/edit/xxoC7I6eikRgp8CYAMMD?p=preview
    – nemesv
    Feb 26, 2015 at 20:07
  • @nemesv, thanks for taking the time to look at this. You've helped me on other questions and I appreciate it. The reason I haven't done what you suggest is because in my real application the <select> will probably be in a template and I only want to make a trip to the server if/when needed. That being said, I could create a customer binding that would do that just before the <select> is used. (Like in a <div> that contains the <select>) Is there already a binding that does that? Something like <div data-bind="call: callAjax()">?
    – Jeff
    Feb 26, 2015 at 21:02

1 Answer 1

1

At this point, I think my best option is to use a computed and try and figure out a different way to get the arguments, but I'd like to understand why using a plain function doesn't work.

Binding handlers in Knockout use a computed observable to update the UI whenever any observable in the binding is updated. When such an update occurs, the binding handler re-reads the binding value, which causes the function to be called again. This method ensures that the binding always gets the correct, latest value, regardless of how the binding itself was constructed.

Using a computed observable for getAvailableCountries provides separation between tracking when to get updated data from the server and when to update the view with that data. This is especially useful when you need to load new data in response to other observables, and this pattern is explained quite well on the Knockout wiki.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.