如何避免在初始化数据绑定下拉列表时触发订阅

How to avoid subscriptions from firing on the initialization of data-bound dropdowns?

本文关键字:下拉列表 何避免 初始化 数据绑定      更新时间:2023-09-26

我想找到最佳实践,以避免在页面启动时启动可观察到的订阅。

问题:

当你有类似下面描述的例子时,启动时会显示警报,这是不需要的:

foo.someProperty = ko.observable(null);
foo.someProperty.subscribe(function () { alert(foo.someProperty()); });

不便的解决方案:

到目前为止,我一直在使用以下解决方案:

foo.someProperty.subscribe(function () {
  if (TriggersEnabled()) { alert(foo.someProperty()) };
});

TriggersEnabled检查避免了回调执行,但此解决方案要求创建TriggersEnabled属性。此外,它必须在启动前设置为false,在完成页面加载后设置为true。

问题

我能避免这种情况吗?有没有其他方法可以达到同样的效果?

根据您提供的fiddle,事件正在触发,因为您绑定到select元素的默认值不是列表中的值。因此,当选择列表显示时,它会更改绑定到第一个选项的可观测值。

解决此问题的方法是确保绑定到select元素的observable的默认值是有效值。

示例:

var page = new PageVM();
function PageVM () {
    
    var vm = this;
    
    vm.someProperty = ko.observable(''); //Provide a default value that will be in the select list
    
    vm.someProperty.subscribe(function () { alert(vm.someProperty()); });
};
ko.applyBindings(page);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
foo.someProperty
<select data-bind="value: someProperty">
    <!-- make sure the first option matches the default value of someProperty -->
    <option value="">Select...</option>
    <option value="01">Option 01</option>
    <option value="02">Option 02</option>
</select>