根据单选按钮选择控制div元素的可见性

时间:2013-05-07 03:43:15

标签: javascript knockout.js

我对淘汰赛相对较新,并且想知道是否有更好的方法来控制基于选择单选按钮组的两个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/

1 个答案:

答案 0 :(得分:1)

您目前的做法很好。您需要一个可观察的(toggleGraph)来存储选择,并根据其值显示隐藏您的div

如果要在选择totalgrowth时重用逻辑,可以将检查逻辑从视图移动到viewmodel到计算属性:

<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'
    });
}

但是如果你有很多选择,那么这个解决方案不能很好地扩展,因为你必须创建大量的辅助属性。

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

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.