我如何在另一列值更改的基础上更改一列的值。在下面的代码中,我想使用标记列值更改来更新%列。
HTML:
<table data-bind="foreach: users()">
<thead class="flip-content table-head">
<tr>
<th align="center">Name</th>
<th align="center">Marks</th>
<th align="center">% out of 100</th>
</tr>
</thead>
<tr >
<td data-bind="text: $data.name()"> </td>
<td>
<input data-bind="value: $data.marks()" />
</td>
<td data-bind='text: $data.percent()'></td>
</tr>
</table>
脚本:
var UserModel = function () {
this.users = ko.observableArray([
{
id: 1,
name: ko.observable('Bob'),
marks: ko.observable(0),
percent: ko.computed(function () {
//percentage formula
}, this)
},
{
id: 2,
name: ko.observable('Jane'),
marks: ko.observable(0),
percent: ko.computed(function () {
//percentage formula
}, this)
}
]);
this.selectedUser = ko.observable(this.users()[0]);
}
var userModel = new UserModel();
ko.applyBindings(userModel);
我该怎么做。
答案 0 :(得分:2)
最简单,最常见的解决方案是使用“类”实例而不是普通对象。这些使您可以轻松选择正确的marks
值,因为在构造函数中,this
指向当前用户。
var User = function(id, name, marks) {
this.id = id;
this.name = name;
this.marks = ko.observable(marks);
this.percent = ko.pureComputed(function() {
return this.marks() + "%";
}, this);
}
var UserModel = function () {
this.users = ko.observableArray([
new User(1, "Bob", 10),
new User(2, "Alice", 30),
]);
this.selectedUser = ko.observable(this.users()[0]);
}
var userModel = new UserModel();
ko.applyBindings(userModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table data-bind="foreach: users()">
<thead class="flip-content table-head">
<tr>
<th align="center">Name</th>
<th align="center">Marks</th>
<th align="center">% out of 100</th>
</tr>
</thead>
<tr >
<td data-bind="text: name"> </td>
<td>
<input data-bind="value: marks" />
</td>
<td data-bind='text: percent'></td>
</tr>
</table>
如果绝对需要使用普通对象,则可以在父模型上定义percent
的逻辑,并在视图中传递对当前项目的引用以动态创建计算对象。 (我不建议这样做)
var UserModel = function () {
this.users = ko.observableArray([
{
id: 1,
name: ko.observable('Bob'),
marks: ko.observable(0)
},
{
id: 2,
name: ko.observable('Jane'),
marks: ko.observable(0)
}
]);
this.selectedUser = ko.observable(this.users()[0])
};
UserModel.prototype.percentageFor = function(user) {
return user.marks() + "%";
};
var userModel = new UserModel();
ko.applyBindings(userModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table data-bind="foreach: users()">
<thead class="flip-content table-head">
<tr>
<th align="center">Name</th>
<th align="center">Marks</th>
<th align="center">% out of 100</th>
</tr>
</thead>
<tr >
<td data-bind="text: name"> </td>
<td>
<input data-bind="value: marks" />
</td>
<td data-bind='text: $parent.percentageFor($data)'></td>
</tr>
</table>