功能无法在淘汰赛中访问observableArray

时间:2016-03-30 18:58:18

标签: javascript knockout.js

当我尝试更新observableArray时,我一直收到此错误: '无法获得财产'删除所有'未定义或空引用'

这是我的代码:

var agilityFirmViewModel = {
    test: ko.computed(function () {
        return Pairs[0].Pairs;
    }),

    currentLocation: ko.observableArray(Pairs[0].Pairs[0].Location);

//function to update values in currentLocation
 ChangeLocation: function (practiceGroup) {
        if (practiceGroup === undefined) {
            practiceGroup = '(All Practice Groups)';
        }
        for (var i = 0; i <= Pairs[0].Pairs.length; i++) {
            if (practiceGroup.Department === Pairs[0].Pairs[i].Department) {
                this.currentLocation.removeAll();
                this.currentLocation.push(practiceGroup.Location[i]);
                return root.currentLocation;
            }
        }
    },
}

$(document).ready(function () {
    ko.applyBindings(agilityFirmViewModel);
});

假设每次都通过for循环中的if语句, 无论什么时候到达

this.currentLocation.removeAll();

我得到上面的错误,说currentLocation未定义。我知道currentLocation中有数据,因此可能导致此问题。它可能很简单,但我似乎无法弄明白。谢谢。

我称之为ChangeLocation():

       <li class="nav-sidebar-GreenMenu">
                    <a href="javascript:;" class="draggable-panel" draggable="true">
                        <i id="CategoryIcon" class="glyphicon glyphicon-user"></i>
                        <span class="sidebarTabName"><b>Practice Group</b></span><br />
                        <!--For some reason, changing the margin-left below will change the width of the entire sidebar-->
                        <span id="CurrentItem_TPG" class="currentItem" @*style="margin-left:64px;"*@>(All Practice Groups)</span>
                        <span id="DefaultItem_TPG" style="display:none;">(All Practice Groups)</span>
                        <i class="fa fa-chevron-left pull-right hidden-xs" data-bind=""></i>
                        <span class="arrow open" style="margin-top:-30px;"></span>
                    </a>
                    <ul class="sub-menu">            
                        <!--ko foreach: test()-->
                            <li>  
                                <a href="#" data-bind="text: $data.Department, value: $data.Department, click: $root.ChangeLocation.bind($data.Department)" class="active"></a>
                            </li>
                        <!-- /ko -->
                    </ul>
                </li>

1 个答案:

答案 0 :(得分:1)

问题在于您使用bind的方式。 bind的实际签名是:

  

fun.bind(thisArg [,arg1 [,arg2 [,...]]])

意思是,第一个参数确定函数中this的含义,其余参数设置调用时使用的参数。相反,请尝试将您的点击处理程序更改为:

$parent.ChangeLocation.bind($parent, $data);

这可确保使用ChangeLocation$parent === this

调用$data === practiceGroup