0

我对淘汰赛比较陌生,想知道是否有更好的方法来根据单选按钮组的选择来控制两个 div 元素的可见性。

我想出的东西似乎相当脆弱,如果它们是额外的选项,这个解决方案将无法扩展 imo。

<label>Total</label><input type="radio" name="toggleGraph" value="total" data-bind="checked: toggleGraph"  />
<label>Growth</label><input type="radio" name="toggleGraph" value="growth" data-bind="checked: toggleGraph"  />

<div id="total-graph" data-bind="visible: $root.toggleGraph() === 'total'">
    Total Graph Here
</div>

<div id="growth-graph" data-bind="visible: $root.toggleGraph() === 'growth'">
    Growth Graph Here
</div>



var ViewModel = function() {
    var self = this;
    self.toggleGraph = ko.observable('total');
}

ko.applyBindings(new ViewModel());

http://jsfiddle.net/pqzhL/

4

1 回答 1

1

你目前的方法很好。您需要一个 observable ( toggleGraph) 来存储选择,并根据其值显示隐藏您的div.

如果您想在选择totalor时重用逻辑,growth您可以将检查逻辑从您的视图移动到您的视图模型到计算属性中:

<div id="total-graph" data-bind="visible: isTotalSelected">
    Total Graph Here
</div>

<div id="growth-graph" data-bind="visible: isGrowthSelected">
    Growth Graph Here
</div>

var ViewModel = function() {
    var self = this;
    self.toggleGraph = ko.observable('total');
    self.isTotalSelected = ko.computed(function() {
        return self.toggleGraph() === 'total'
    });
    self.isGrowthSelected = ko.computed(function() {
        return self.toggleGraph() === 'growth'
    });
}

但是,如果您有很多选项,则此解决方案无法很好地扩展,因为您必须创建大量辅助属性。

或者您可以创建一个自定义绑定处理程序,该处理程序执行一些基于约定的检查,将divid 与所选值进行比较:

ko.bindingHandlers.visibleIfIdStartsWith = {
    update: function (element, valueAccessor, allBindingsAccessor, 
                      viewModel, bindingContext) {
        var newAccessor = function () {
            return element.id.indexOf(valueAccessor()()) === 0;
        }
        ko.bindingHandlers.visible.update(element, newAccessor, 
            allBindingsAccessor, viewModel, bindingContext);
    }
};

然后像这样使用它:

<div id="total-graph" data-bind="visibleIfIdStartsWith: toggleGraph">
    Total Graph Here</div>
<div id="growth-graph" data-bind="visibleIfIdStartsWith: toggleGraph">
    Growth Graph Here</div>

演示JSFiddle。

于 2013-05-07T05:11:09.217 回答