【问题标题】:knockoutjs computed not able to access observable value敲除js计算无法访问可观察值
【发布时间】:2014-08-02 04:05:18
【问题描述】:

我想我 99% 都支持这个。我有一个 ko.computed 如果它在数据绑定中引用 observables 就可以工作。但是,当我尝试在 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>

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    您收到错误,因为属性 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);
    

    【讨论】:

      猜你喜欢
      • 2016-09-12
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 2019-07-18
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多