1

我是 KnockoutJS 的新手,我遇到了一些问题。

我不明白为什么selectedOf在点击后没有更新。

有人能发现我做错了什么吗?

<div>
    <ul data-bind="foreach: Ofs">
        <li data-bind="text: Number, click: $root.selectOf" style="cursor:pointer"/>
    </ul>
    <strong>Item clicked: </strong><span data-bind="text: selectedOf.Number" />
</div>

<script type"text/javascript">
    var OfsModel = function (initialData) {
        //console.log(initialData);
        var self = this;
        self.CurrentState = ko.observable(initialData.CurrentState);
        self.Ofs = ko.observableArray(initialData.Ofs);
        self.selectedOf = ko.observable();

        self.selectOf = function (of) {
            //console.log(of);
            self.selectedOf(of);
            //console.log(self.selectedOf());
        }
    }

    var initialData = '{"Ofs":[{"Client":"A","Number":"1","Qty":10,"QtyRejected":5,"StopReason":"","ModifiedOn":"\/Date(1345732172456)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"},{"Id":3,"Name":"Seq3"}],"SelectedSequence":null},{"Client":"B","Number":"2","Qty":20,"QtyRejected":0,"StopReason":"too much work","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"}],"SelectedSequence":null},{"Client":"C","Number":"3","Qty":30,"QtyRejected":0,"StopReason":"","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"}],"SelectedSequence":null}],"CurrentState":""}';

    var vw = $.parseJSON(initialData);
    ko.applyBindings(new OfsModel(vw));
</script>

编辑:我把代码放在http://jsfiddle.net/muek/KBeZ3/2/

4

1 回答 1

1

当您访问 的Number属性时selectedOf,您需要首先通过将其作为不带参数的函数调用来获取可观察对象的值selectedOf().Number

但是,如果您在selectedOf填充之前执行此操作,则会导致尝试访问Number未定义值时出错。

解决这个问题的一个好方法是使用with绑定之类的东西来设置元素子元素的范围。它还可以防止空值。这看起来像:

<div data-bind="with: selectedOf">
    <strong>Item clicked: </strong><span data-bind="text: Number" />
</div>

这是一个示例:http: //jsfiddle.net/rniemeyer/ecDgD/

Number或者,您可以为防止 null 或绑定之类的值创建一个计算的 observabledata-bind="text: selectedOf() ? selectedOf().Number : 'none'"

于 2012-08-23T14:59:59.610 回答