ko.computed只适用于最后一行

时间:2016-01-09 22:17:48

标签: javascript jquery knockout.js

这是我的HTML:

<table>
    <thead>
        <tr>
            <th>Name:</th>
            <th>Last Name</th>
            <th>Full Name:</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: person">
        <tr>
            <td><input data-bind="value: name"/></td>
            <td><input data-bind="value: lastname"/></td>
            <td data-bind="text: fullname"></td>
        </tr>
    </tbody>
</table>

JS

function newPerson(){
    self = this;
    self.name = ko.observable();
    self.lastname = ko.observable();
    self.fullname = ko.computed(function(){
      var name_full = self.name() + " " +self.lastname();
      return name_full;
    });
}

function personsViewModel(){
    var self = this;
    self.person = ko.observableArray([
        new newPerson(),
        new newPerson()
    ]);
}

$(function(){
    ko.applyBindings(new personsViewModel());
})

显然我的代码没有任何问题,但是当你运行脚本时,事件只服务于最后一行;也就是说,第二行仅用于为所有行生成事件全名。

ko.computed事件仅用于其他行不接受事件的最后一行。

1 个答案:

答案 0 :(得分:3)

您需要使用var,否则self每次执行newPerson时都会覆盖全局范围。

function newPerson(){
    var self = this; // <=== change is here
    self.name = ko.observable();
    self.lastname = ko.observable();
    self.fullname = ko.computed(function(){
      var name_full = self.name() + " " +self.lastname();
      return name_full;
    });
}

function personsViewModel(){
    var self = this;
    self.person = ko.observableArray([
        new newPerson(),
        new newPerson()
    ]);
}

$(function(){
    ko.applyBindings(new personsViewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
    <thead>
        <tr>
            <th>Name:</th>
            <th>Last Name</th>
            <th>Full Name:</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: person">
        <tr>
            <td><input data-bind="value: name"/></td>
            <td><input data-bind="value: lastname"/></td>
            <td data-bind="text: fullname"></td>
        </tr>
    </tbody>
</table>

我建议您在文件中使用strict mode,以及在构建设置中使用jshint这样的javascript linter,因为我认为两者都会遇到您遇到的问题类型。