0

So I have a checkbox, and I'm trying to implement the following logic to set the visibility:

If checkbox is checked OR the checkbox's value is below a specified number, set visible = true.

If the value exceeds the test value AND the checkbox is not checked, hide it.

Here is what I have so far:

<input type="checkbox" data-bind="visible: $data.Cost <= $root.itemLevel() - $root.totalEnchantLevelsUsed() || checked" />

I have tried several variations of getting 'checked', including changing 'checked' to $root.isChecked:

this.isChecked = ko.computed ( function (item) { 
  console.log('item', item); // PURELY TO TEST THE VALUE
}

But that is telling me that 'item' is undefined. When I try to explicitly pass in $data, I get an error message about ko.computed and having to set 'write' access.

Is there not a relatively simple way to do this that I'm just overlooking? Admittedly I'm not super familiar with knockout.

4

1 回答 1

1

Here is something similar to what you're trying to do: http://jsfiddle.net/2aXrJ

Html:

<div data-bind="foreach:items">
    <label data-bind="visible: isAllowedInWorkflow">
        <input data-bind="value: val" type="checkbox" />
        This checkbox has value
        <span data-bind="text:val"></span>
    </label>
</div>

jS:

ko.applyBindings({
    items: [createItem(10), createItem(20), createItem(30) ]
})

function createItem(val) {
    var  _item = {
         val: val
        ,isSelected: ko.observable(false)
    };
    _item.isAllowedInWorkflow = ko.computed(function() {
        //notice the order is importeant since you always want isSelected to be triggered for the 
        //computed to calculate its dependencies
        return !_item.isSelected() && val > 10; 
    });
    return _item;
}
于 2013-10-20T19:18:17.137 回答