2

我现在可能是个菜鸟,但问题来了。我有一个由 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>

我在这里要完成的是,每当单击列表项时,都会显示预先填充了单击用户信息的编辑表单。关于如何实现这一点的任何提示或技巧对你们来说都非常棒。谢谢。

4

1 回答 1

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/

于 2012-08-21T16:06:20.493 回答