1

I've been following the simple editor pattern on knockmeout and everything worked as expected until I started using nested objects.

Basically when I select an item I'm setting 2 properties on my viewmodel. A selectedItem property and an editable property. It's the editable property that I then make changes to. If the user accepts the changes then the selected item is updated.

This works fine in my code if I have a flat object. However when I have nested objects the child objects data is not correct when assigned to the editable property.

I should see:

"Selected": {
    "Id": 1,
    "Name": "user 1",
    "Role": {
      "Id": 2,
      "RoleName": "IT Support"
    }
  },
  "Editable": {
    "Id": 1,
    "Name": "user 1",
    "Role": {
      "Id": 2,
      "RoleName": "IT Support"
    }

However I get:

"Selected": {
    "Id": 2,
    "Name": "user 1",
    "Role": {
      "Id": 3,
      "RoleName": "IT Procurement"
    }
  },
  "Editable": {
    "Id": 2,
    "Name": "user 1",
    "Role": {
      "Id": 2,
      "RoleName": "IT Support"
    }

If I log the details object passed to the selectItem method I can see the data is correct. It just doesn't seem to be correct when assigned to the editable property.

Apologies if this isn't very clear. Here is a link to my fiddle

4

1 回答 1

0

您遇到的问题来自select编辑器中的绑定。Knockout 确保您的当前值是有效选择,或者将其设置为第一个条目。EmployeeRoles在您的情况下,您的可编辑副本对数组中的项目没有相同的引用。尽管它们看起来相同,但它们彼此并不相等,因为它们不是同一个参考。

一个简单的解决方法可能是执行以下操作:

self.SelectEmployee = function(e){
    self.Selected(e);
    var copy = ko.toJS(e);
    copy.Role = e.Role(); //get the actual reference
    self.Editable(new Employee(copy));
    self.isOpen(true);
};

因此,我们仍然使用ko.toJS制作干净的副本,然后将实际引用粘贴到Role副本上。

更新示例:http: //jsfiddle.net/rniemeyer/rVYrB/

您的示例是将这种模式与弹出对话框结合使用的一个很好的例子。

于 2013-07-24T13:41:15.443 回答