设置默认值后,KnockoutJS select触发onChange [英] KnockoutJS select fires onChange after setting default value
问题描述
我在页面上设置了以下选择以更改学期.当选择检测的变化,则
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屋!