kindohm
kindohm

Reputation: 1600

can't get knockout.js dependent observable chaining to work

I'm having trouble getting a simple dependentObservable chain to work in knockout.js. Here is my code:

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>

Whenever the "are you still working" radios are checked, the didYouQuitVisible dependentObservable never seems to update or fire. I have an alert() in there, and an alert never pops up whenever the "are you still working" radios are checked/unchecked. However, the alert DOES show up when the first radio group is checked/unchecked. The first dependentObservable (stillWorkingVisible) works just fine. Ideas?

Upvotes: 2

Views: 1357

Answers (2)

neeebzz
neeebzz

Reputation: 11538

Working version: http://jsfiddle.net/SvHxY/

stillWorkingVisible() is returning a bool

Upvotes: 1

St&#233;phane Bebrone
St&#233;phane Bebrone

Reputation: 2763

Your code seems to be wrong on this assertion:

    return this.stillWorkingVisible() == 'Yes' 

stillWorkingVisible() would never return a string 'Yes' but a bool.

Edit

The fiddle seems to work as expected with the fix.

Upvotes: 3

Related Questions