knockoutjs计算无法访问可观察值

时间:2014-06-11 23:14:30

标签: javascript knockout.js

我想我99%有这个。我有一个ko.computed,如果它引用了数据绑定中的observable,它就可以工作。但是,当我尝试在ko.computed中获取observable的值时,我得到一个错误。这是小提琴http://jsfiddle.net/rZLjE/9/,因为您可以根据需要查看绑定到plusTwo().name更新的范围。基于这个事实,我觉得让plusOne()返回像self.selectedData().name + "other text"这样的东西应该有用,但这会产生错误。

我对此代码的理解不清楚?

感谢。

和后代的代码

function Student(data) {
  this.name = ko.observable(data);
};

function ViewModel(students) {
  var self = this;
  self.students = ko.observableArray([]);
  self.selectedData = ko.observable();
  self.plusOne = ko.computed(function () {
    return self.selectedData() + " why can't I get this to combine with selectedData!!!!";}, this);
  self.plusTwo = ko.computed(function () {
    return this.selectedData();
  }, this);
  students.forEach(function (student) {
    self.students.push(new Student(student));
  });};
var initData = ["koa", "pine", "rosewood"];
window.appViewModel = new ViewModel(initData);
ko.applyBindings(window.appViewModel);

HTML:

<table>
<tr style="vertical-align:top">
    <td>
        <table border="1">
            <thead>
                <tr>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: students">
                <tr>
                    <td>
                        <input type="text" data-bind="value: name, valueUpdate: 'keyup', event: {focus: $parent.selectedData}" />
                    </td>
                </tr>
            </tbody>
        </table>
    </td>
    <td>
        <div data-bind="if: selectedData"> 
            <span data-bind="text: selectedData().name"></span>
            <br/>
            <br/>
            <span data-bind="text: plusOne()"></span>
            <br/>
            <br/>
            <span data-bind="text: plusTwo().name"></span>
        </div>
    </td>
</tr>

1 个答案:

答案 0 :(得分:0)

由于未初始化属性selectedData,因此收到错误。使用空的学生对象进行初始化将解决您的问题。

jsFiddle here

 self.selectedData = ko.observable(new Student(''));

 self.plusOne = ko.computed(function () {
        return  this.selectedData().name() 
                      + " I can now combine with selectedData!!!!";
}, this);