2013-02-10 90 views
2

我有一個帶有兩個虛擬機的主視圖模型,它是通過映射插件創建的。在視圖模型問題更新後的knockoutjs數據操作

viewModelObj = { 
    first   : new firstVM(), 
    second   : new secondVM() 
} 

viewModel = mapping.fromJS(viewModelObj, mappingOptions); 
ko.applyBindings(viewModel); 

的數據是這樣的:

'firstObj'  : { 
    'title'   : 'CURRENT title goes here', 
    'children'  : [ 
     { 'id': '00001', 'name': 'Rube no 1' }, 
     { 'id': '00002', 'name': 'Rube no 2' }, 
     { 'id': '00003', 'name': 'Rube no 3' } 
    ], 
    'warning' : false 
}, 
'secondObj'  : { 
    'title'   : 'Second Item title' 
} 

firstVM有observableArray孩子

self.children = ko.observableArray(item.children); 

self.calLength = ko.computed(function() { 
    return 'Total ' + self.children().length; 
}); 

似乎一切,直到我更新的數據很好地工作。更新的數據:

'firstObj' : { 
    'title'  : 'UPDATED TITLE goes here', 
    'children' : [ 
     { 'id': '00004', 'name': 'Rube no 4' }, 
     { 'id': '00005', 'name': 'Rube no 5' }, 
     { 'id': '00006', 'name': 'Rube no 6' }, 
     { 'id': '00007', 'name': 'Rube no 7' }, 
     { 'id': '00008', 'name': 'Rube no 8' }, 
     { 'id': '00009', 'name': 'Rube no 9' } 
    ], 
    'warning' : true 
}, 
'secondObj'  : { 
    'title'   : '2nd Title UPDATED' 
} 

在HTML first.children()返回長度更新數組的長度是否正確,foreach.children也能正常工作,但在VM calLength()函數不返回更新的長度。爲什麼?

它看起來像所有的數據更新成功,但不能訪問虛擬機功能,如果它是一個數組(我可以很容易地得到self.title()或其他可觀察的數據)。也許mappingOptions有一些問題?

'first' : { 
    create : function(options) { 
     return mapping.fromJS(options.data, {}, this); 
    } 
}, 
'second' : { 
    create : function(options) { 
     return mapping.fromJS(options.data, {}, this); 
    } 
} 

這是一個完整的演示:

http://jsfiddle.net/simoncereska/bfvgT/

附:如果您有任何其他意見,歡迎您發表:)

非常感謝。

回答

1

確保您的子可觀察數組正在使用新值進行更新,而不是用新的可觀察數組替換。