设置默认值后,KnockoutJS select触发onChange [英] KnockoutJS select fires onChange after setting default value

查看:605
本文介绍了设置默认值后,KnockoutJS select触发onChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上设置了以下选择以更改学期.当选择检测的变化,则功能被触发,它运行的是替换数据特定于所选学期页面上的当前数据的AJAX.

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.

查看

<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
};

问题在于,当页面加载并设置默认值时,select中的change事件将触发changeSemester函数.有没有一种方法可以避免这种情况,而无需使用按钮?

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?

推荐答案

通常,在这些情况下,您想要使用的是

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.

因此,您可以这样做:

this.selectedSemester.subscribe(changeSemesters, this);

如果selectedSemester由于绑定而仍在更改,则可以将其初始化为默认值.

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);

这篇关于设置默认值后,KnockoutJS select触发onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆