无法获得knockout.js依赖可观察的链接工作

时间:2011-12-12 18:49:53

标签: javascript knockout.js

我无法在knockout.js中使用简单的dependentObservable链。这是我的代码:

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" />&nbsp;No
        <input type="radio" name="didWork" value="Yes" data-bind="checked: didWork" />&nbsp;Yes
    </li>
    <li data-bind="visible: stillWorkingVisible">Are you still working?<br />
        <input type="radio" name="stillWorking" value="No" data-bind="checked: stillWorking" />&nbsp;No
        <input type="radio" name="stillWorking" value="Yes" data-bind="checked: stillWorking" />&nbsp;Yes
    </li>
    <li data-bind="visible: didYouQuitVisible">Did you quit?<br />
        <input type="radio" name="didYouQuit" value="No" data-bind="checked: didYouQuit" />&nbsp;No
        <input type="radio" name="didYouQuit" value="Yes" data-bind="checked: didYouQuit" />&nbsp;Yes
    </li>
</ul>

每当“你还在工作”的无线电被检查时,didYouQuitVisible dependentObservable似乎永远不会更新或触发。我在那里有一个警报(),每当“你还在工作”的无线电被检查/取消选中时,都不会弹出警报。但是,当检查/取消选中第一个无线电组时,警报会显示。第一个dependentObservable(stillWorkingVisible)工作得很好。想法?

2 个答案:

答案 0 :(得分:3)

你的代码似乎在这个断言上是错误的:

    return this.stillWorkingVisible() == 'Yes' 

stillWorkingVisible()永远不会返回字符串'是',而是bool

修改

fiddle似乎与修复工作一样正常。

答案 1 :(得分:1)

工作版本:http://jsfiddle.net/SvHxY/

stillWorkingVisible()正在返回一个bool