【问题标题】:Knockout visible binding not getting reevaluated淘汰赛可见绑定没有得到重新评估
【发布时间】:2013-04-23 08:22:17
【问题描述】:

我对淘汰赛可见绑定有点困惑。 我创建了一个示例来演示该问题。 主要目标是在用户选择“其他”选项时显示一些 div (otherDetails)。 它不工作。 更改“mySelection”字段时,不会重新评估可见的。

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Test</title> 

    <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script> 
    <script src="Scripts/knockout-2.2.0.js" type="text/javascript"></script> 

    <script type="text/javascript"> 

    function data() 
    { 
            this.mySelection =  ko.observable('other'); 

            this.isOtherSelected = ko.computed(function () 
            { 
                    return this.mySelection.peek() == 'other'; 
            }, this); 
    } 

    var myData = new data(); 

    $(document).ready(function () 
    { 
             $('#selections').change(function () 
             { 
                 myData.mySelection = $(this).val();         
             }); 

            dataBind(); 
    }); 

    function dataBind() 
    { 
            ko.applyBindings(myData); 
    } 
    </script> 
</head> 

<body> 
        <div> 
                <select id="selections" data-bind="value: mySelection"> 
                    <option value='one'>One</option> 
                    <option value='two'>Two</option> 
                    <option value='three'>Three</option> 
                    <option value='other'>Other</option> 
                </select> 
        </div> 
        <div id="otherDetails" data-bind="visible: isOtherSelected"> 
            <span>Some controls and stuff...</span> 
        </div> 
</body> 

提前致谢,亚龙。

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    只需删除peek():
    return this.mySelection() == 'other';

    peek 函数获取 observable 的值,但不订阅外部计算的 observable 更改。因此,您的绑定不会被重新评估。

    【讨论】:

      【解决方案2】:

      您应该以不同的方式使用 observables。每个 observable 都是一个函数,因此要获得价值,您必须调用它:

      return this.mySelection() == 'other';
      

      如果你想给它赋值,你应该将值传递给这个函数:

      myData.mySelection($(this).val());  
      

      这是工作小提琴:http://jsfiddle.net/kkGRs/

      附:您不需要在那里使用 jQuery 更改处理程序。 KO 会自动更新 observable 的值。这是重构代码:http://jsfiddle.net/kkGRs/1/

      【讨论】:

        猜你喜欢
        • 2017-05-11
        • 1970-01-01
        • 2012-11-14
        • 2013-08-30
        • 2012-03-20
        • 2013-02-04
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        相关资源
        最近更新 更多