我是knockout.js的新手,我不知道如何使用我的对象进行多次映射.
这是我从服务器获取的数据:
var persons = {
'value': [
{
"id": "1","civility": "Mr.","firstname": "john","lastname": "doe","phone": "00 00 00 00 00","email": "email@email.com","contract": [
{
"id": "1","gamme": "Gamme 1","formula": "Formula 1"
},{
"id": "2","gamme": "Gamme 2","formula": "Formula 2"
}
]
}
]
}
我对整个对象进行了第一次映射,并计算了一些数据:
var person_mapping = {
'value': {
create: function (options) {
if (options.data != null) {
return new myPersonModel(options.data);
}
}
}
}
var myPersonModel = function (data) {
ko.mapping.fromJS(data,{},this);
this.fullName = ko.computed(function () {
return this.civility() + ' ' + this.lastname() + ' ' + this.firstname();
},this);
}
执行完之后,我得到了我想要的第一部分:
self.dataModel = ko.mapping.fromJS(persons,person_mapping);
但是现在,我想对person对象中的contract数组做同样的事情,也就是说应用一个映射并做一些像这样的ko.computed:
var contract_mapping = {
'contract': {
create: function (options) {
if (options.data != null) {
return new myContractModel(options.data);
}
}
}
}
var myContractModel = function (data) {
ko.mapping.fromJS(data,this);
this.contractName = ko.computed(function () {
return this.gamme() + ' ' + this.formula();
},this);
}
但我不知道如何应用我的第二个映射,似乎没什么用.
最佳答案
您可以在myPersonModel的第一行中应用第二个映射.您可以在您正在使用的每个构造函数中嵌套映射策略.
原文链接:https://www.f2er.com/js/429185.htmlvar myPersonModel = function(data) {
ko.mapping.fromJS(data,contract_mapping,this);
/* ... */
};
var persons = {
'value': [{
"id": "1","contract": [{
"id": "1","formula": "Formula 1"
},{
"id": "2","formula": "Formula 2"
}
]
}]
}
var contract_mapping = {
"contract": {
create: function(options) {
return new myContractModel(options.data);
}
}
}
var person_mapping = {
'value': {
create: function(options) {
if (options.data != null) {
return new myPersonModel(options.data);
}
}
}
}
var myContractModel = function(data) {
ko.mapping.fromJS(data,this);
this.type = "myContractModel";
};
var myPersonModel = function(data) {
ko.mapping.fromJS(data,this);
this.fullName = ko.computed(function() {
return this.civility() + ' ' + this.lastname() + ' ' + this.firstname();
},this);
}
console.log(
ko.mapping.fromJS(persons,person_mapping)
.value()[0]
.contract().map(x => x.type)
);