我一直在努力制作一个交互式表单,其中 View 模型具有项目集合。我想从该集合中动态添加/删除项目。
我发现很难找到如此深入的示例,并且大多数示例通常停留在更直接的实现上,但是我遇到过 This post这几乎解释了我正在用这个出色的jsfiddle做什么,其中使用knockout映射插件拉取一个json,然后进行映射。
var company;
function PersonViewModel(data) {
var personMapping = {
'ignore': ['twitter', 'webpage'],
'copy': ['age'],
'lastName': {
'create': function (options) {
return ko.observable(options.data.toUpperCase());
}
}
};
ko.mapping.fromJS(data, personMapping, this);
this.fullName = ko.computed(function () {
return this.firstName() + ' ' + this.lastName();
}, this);
}
function CompanyViewModel(data) {
var companyMapping = {
'ignore': ['address', 'website'],
'name': {
'create': function (options) {
return ko.observable(options.data.toUpperCase());
}
},
'employees': {
key: function (data) {
return ko.utils.unwrapObservable(data.personId);
},
create: function (options) {
return new PersonViewModel(options.data);
}
}
};
ko.mapping.fromJS(data, companyMapping, this);
}
我不知道如何实现如何以及在哪里到底添加'addEmployee'和'removeEmployee'函数?以及如何将它们绑定(bind)到按钮?
提前谢谢您!
最佳答案
添加这些内容的合理位置是您的 CompanyViewModel
。例如,像这样:
function CompanyViewModel(data) {
var self = this;
var companyMapping = {
// ...as before
};
self.addEmployee = function () {
// as an example, we are just adding a static new employee
self.employees.push(new PersonViewModel({
lastName: "new",
firstName: "employee",
age: 10
}));
}
// important, with how we are binding the function, we expect the
// argument, e, to be the employee to remove
self.removeEmployee = function (e) {
self.employees.remove(e);
}
ko.mapping.fromJS(data, companyMapping, this);
}
添加到绑定(bind)中,你可以这样做:
<div id="company">
<h1 data-bind="text: name"></h1>
<h2>Employees</h2>
<input type="button" value="add" data-bind="click: addEmployee" />
<table>
<thead>
<tr>
<th>Full name</th>
<th>Last name</th>
<th>First name</th>
<th>Age</th>
</tr>
</thead>
<tbody data-bind="foreach: employees">
<tr>
<td data-bind="text: fullName"></td>
<td data-bind="text: lastName"></td>
<td data-bind="text: firstName"></td>
<td data-bind="text: age"></td>
<td>
<input type="button" value="x" data-bind="click: $parent.removeEmployee" />
</td>
</tr>
</tbody>
</table>
</div>
这将添加 add
按钮以及删除 x
按钮给每个员工,调用 removeEmployee
父函数CompanyViewModel
传入当前员工。
这是更新的 fiddle
关于javascript - 使用 Knockoutjs 在客户端添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34045989/