当我们第一次应用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
答案 0 :(得分:2)
不是循环遍历数组并将comp
计算的observable添加到每个项目,而是设置映射,以便在创建项目时添加它们。
var mapping = {
'list': {
key: function (data) {
return ko.utils.unwrapObservable(data.name);
},
create: function (options) {
var mapped = ko.mapping.fromJS(options.data, {
'list': {
key: function (data) {
return ko.utils.unwrapObservable(data.name);
},
create: function (options) {
var mapped = ko.mapping.fromJS(options.data);
return ko.utils.extend(mapped, {
comp: ko.computed(function () {
return this.val() * 3;
}, mapped)
});
}
}
});
return ko.utils.extend(mapped, {
comp: ko.computed(function () {
return this.val() * 2;
}, mapped)
});
}
},
'name': {
key: function (data) {
return ko.utils.unwrapObservable(data.name);
}
}
};
var model = ko.mapping.fromJS(modelJs, mapping);