我在使简单的dependentObservable链在knockout.js中工作时遇到麻烦。这是我的代码:
var viewModel = {
didWork: ko.observable(''),
stillWorking: ko.observable(''),
didYouQuit: ko.observable('')
};
viewModel.stillWorkingVisible = ko.dependentObservable(function () {
return this.didWork() == 'Yes';
}, viewModel);
viewModel.didYouQuitVisible = ko.dependentObservable(function () {
alert('ok');
return this.stillWorkingVisible() == 'Yes' && this.stillWorking() == 'No';
}, viewModel);
ko.applyBindings(viewModel);
<ul>
<li>Did you do any work?<br />
<input type="radio" name="didWork" value="No" data-bind="checked: didWork" /> No
<input type="radio" name="didWork" value="Yes" data-bind="checked: didWork" /> Yes
</li>
<li data-bind="visible: stillWorkingVisible">Are you still working?<br />
<input type="radio" name="stillWorking" value="No" data-bind="checked: stillWorking" /> No
<input type="radio" name="stillWorking" value="Yes" data-bind="checked: stillWorking" /> Yes
</li>
<li data-bind="visible: didYouQuitVisible">Did you quit?<br />
<input type="radio" name="didYouQuit" value="No" data-bind="checked: didYouQuit" /> No
<input type="radio" name="didYouQuit" value="Yes" data-bind="checked: didYouQuit" /> Yes
</li>
</ul>
每当检查“您还在工作”无线电时,didYouQuitVisible依赖的Observable似乎永远不会更新或触发。我在那里有一个alert(),并且无论何时选中/取消选中“您还在工作中”的收音机,都不会弹出警报。但是,当第一个无线电组被选中/未选中时,将显示警报。第一个dependentObservable(stillWorkingVisible)可以正常工作。有想法吗?
最佳答案
您的代码在此断言上似乎是错误的:
return this.stillWorkingVisible() == 'Yes'
stillWorkingVisible()
绝不会返回字符串“是”,而只会返回bool
。编辑
fiddle似乎可以通过修复程序正常工作。