我现在可能就是这样一个noobie,但这是问题所在。我有一个由knockoutjs生成的用户列表。这是我正在使用的基本代码(跳过所有不必要的细节):
function User(info) {
this.id = info.id;
this.firstName = ko.observable(info.firstname);
this.lastName = ko.observable(info.surname);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
}
function HrManagementViewModel() {
var self = this;
self.users = ko.observableArray([]);
$.getJSON("/users", function (data) {
var mappedUsers = $.map(data, function (item) { return new User(item); });
self.users(mappedUsers);
});
}
HTML代码如下所示:
<ul data-bind="foreach: users">
<li data-bind="text: fullName"></li>
</ul>
我想在这里完成的是每当点击列表项时,编辑表单会显示预先填充的点击用户信息。关于如何实现这一目标的任何提示或技巧对你们来说都是非常棒的。感谢。
答案 0 :(得分:3)
ko.applyBindings()
函数有一个可选的第二个参数,可用于指定要搜索数据绑定属性的元素。所以你可以做这样的事情:
<ul data-bind="foreach: users">
<li data-bind="text: fullName, click: $parent.showForm"></li>
</ul>
<hr/>
<form id="form">
<p><input data-bind="value: id"></input></p>
<p><input data-bind="value: firstName"></input></p>
<p><input data-bind="value: lastName"></input></p>
</form>
然后,在HrManagementViewModel中:
self.currentUser = ko.observable(null);
self.showForm = function(user, event) {
// first argument here is the item, associated with the <li> element
// second - the event object.
var previousSelection = self.selectedUser();
self.selectedUser(user); // Wrap your user viewModel in observable. To change
// the input fields bindings just update it
// with a new viewModel and KO will do the rest.
if (previousSelection == null) {
var target = document.getElementById('form');
ko.applyBindings(self.selectedUser, target);
}
}
在这里,试一试:http://jsfiddle.net/mH3fx/4/