KnockoutJS select fires onChange after setting def

2019-08-05 04:58发布

问题:

I have set up the following select for changing semesters on page. When the select detects a change, the changeSemesters function is fired, which runs an AJAX that replaces the current data on the page with data specific to the selected semester.

View

<select data-bind="options: semestersArr, optionsText: 'name', optionsValue: 'id', value: selectedSemester, event: { change: changeSemesters }"></select>

ViewModel

this.selectedSemester = ko.observable();

//runs on page load
var getSemesters = function() {
  var self = this, current;

  return $.get('api/semesters', function(data) {
    self.semestersArr(ko.utils.arrayMap(data.semesters, function(semester) {
      if (semester.current) current = semester.id;
      return new Model.Semester(semester);
    }));

    self.selectedSemester(current);
  });
};

var changeSemesters = function() {
  // run ajax to get new data
};

The problem is that the change event in the select fires the changeSemester function when the page loads and sets the default value. Is there a way to avoid that without the use of a button?

回答1:

Generally what you want to do in these scenarios is to use a manual subscription, so that you can react to the observable changing rather than the change event. Observables will only notify when their value actually changes.

So, you would do:

this.selectedSemester.subscribe(changeSemesters, this);

If selectedSemester is still changing as a result of getting bound, then you can initialize it to the default value.

this.selectedSemester = ko.observable(someDefaultValue);