无法使用新数据对象更新Knockout UI

jaf*_*ffa 6 javascript knockout.js

当我从服务器获取单个项目的新数据时,我正在遇到UI刷新问题,该项目位于包含多个可观察对象的包装对象的observableArray中.

考虑以下:

var vm = {
....
localEdited: ko.mapping.fromJS(new ItemWrapper(defaultModelSerialised)), 
selected: ko.observable(null),
editItem: function(data) {
  // clone a temporary copy of data for the dialog when opening (*.localEdited on dialog)
  var clonedData = ko.toJS(data);
  ko.mapping.fromJS(clonedData, null, this.localEdited);

  // selected should now point to the item in the obserable array which will be refreshed
  this.selected(data);

  // open dialog...
},
submitDialog: function(data) {

   // submit data to server...

   // (1) commit the data back to UI (new item is return in resp.entity from server)
   vm.selected(new ItemWrapper(resp.entity));

   // at this point the UI isn't showing the updated value

   // (2) however if I do this it reflects the data change in the UI
   this.selected().Name("changed");  // updates the UI.
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么将ItemWrapper传入vm.selected不会更新UI,而在(2)中它可以工作.我不想为每个属性设置像(2)中的每个属性.

ItemWrapper看起来像这样:

function PoolWrapper(pool) {
    this.Name = ko.observable(pool.Name);

    // more properties...
} 
Run Code Online (Sandbox Code Playgroud)

RP *_*yer 6

好的 - 问题是你的克隆最终会在它们上映射元数据,并最终在尝试调用时导致递归ko.mapping.fromJS.

解决方案是使用ko.mapping.toJS而不是创建克隆ko.toJS,以便获得干净的克隆(不映射元数据).

这是一个更新的小提琴:http://jsfiddle.net/rniemeyer/tDDBp/