当我们第一次应用 ViewModel 时一切正常,但是如果我们在创建计算字段后重新应用映射,它们就会被删除。如果我们不更改密钥,这段代码显然可以工作
http://jsbin.com/ojabaf/14/edit
var modelJs = {test:{
list: [{name: 'a', val: 5, list: [ {name:'b', val: 11}, {name: 'c', val: 13} ]}]}
};
var mapping = {
'list': {
key: function(data) { return ko.utils.unwrapObservable(data.name); }
},
'name': {
key: function(data) { return ko.utils.unwrapObservable(data.name); }
}
};
var model = ko.mapping.fromJS(modelJs, mapping);
ko.utils.arrayForEach(model.test.list(), function(item) {
item.comp = ko.computed({read: function() { return this.val() * 2; } , owner: item });
ko.utils.arrayForEach(item.list(), function(item2) {
item2.comp = ko.computed({read: function() { return this.val() * 3; } , owner: item2 });
});
});
ko.applyBindings(model);
$('button').click(function () {
var modelJs = {test: {val: 3, list: [{name: 'b', val: 7, list: [ {name:'s', val: 15}, {name: 'c', val: 17} , {name: 'd', val: 17}, {name: 'f', val: 17}]}]}};
ko.mapping.fromJS(modelJs, model);
});
有没有办法用 ko.mapping 重新计算那些计算字段,而不刷新页面?
我也尝试过使用模板... http://jsbin.com/ojabaf/15/edit