大家好, 請問一下各位, 因為下面的this.chartGroup 之後會不停加入新的record, 可以怎樣把這一部分抽出來(新class?新的file), 再include 到這個class 的constructor, 謝謝
class chartAction {
constructor() {
this.svg;
this.chartGroup = {
"rf3": {
initgrid: 16,
title: '1-hour Rainfall / mm',
domain: [0, 0],
intv: 5,
ylabel_unit: 'mm',
ylabel: '',
def_station: '[30 HK Grids] ',
sel_station: '[30 HK Grids] ',
unit: ' mm',
dp: 1
},
"spd": {
initgrid: 11,
title: '10-m Wind Speed / m s\u207b\u00b9',
domain: [0, 0],
intv: 5,
ylabel_unit: 'm s\u207b\u00b9',
ylabel: '',
def_station: '[WGL] ',
sel_station: '',
unit: ' m s\u207b\u00b9',
dp: 1
},
"dir": {
initgrid: 11,
title: '10-m Wind Direction',
domain: [0, 360],
intv: 90,
ylabel_unit: '',
ylabel: '',
def_station: '[WGL] ',
sel_station: '',
unit: '\u00b0',
dp: 1
},
...
}
}
}
若有特別的指定型態需求,用 Typescript
比較方便JS
我可能會設計成:
class ChartAction {
constructor() {
this.svg;
this.chartGroup = {};
}
addRecord(data) {
if (data instanceof ChartData) {
this.chartGroup = Object.assign(this.chartGroup, data);
} else {
throw new Error('Type error');
}
}
printGroup() {
console.log(this.chartGroup);
}
}
class ChartData {
constructor(
key,
initgrid,
title,
domain,
intv,
ylabel_unit,
ylabel,
def_station,
sel_station,
unit,
dp
) {
this[key] = {
initgrid,
title,
domain,
intv,
ylabel_unit,
ylabel,
def_station,
sel_station,
unit,
dp
}
}
}
let testData = {
"rf3": {
initgrid: 16,
title: '1-hour Rainfall / mm',
domain: [0, 0],
intv: 5,
ylabel_unit: 'mm',
ylabel: '',
def_station: '[30 HK Grids] ',
sel_station: '[30 HK Grids] ',
unit: ' mm',
dp: 1
},
"spd": {
initgrid: 11,
title: '10-m Wind Speed / m s\u207b\u00b9',
domain: [0, 0],
intv: 5,
ylabel_unit: 'm s\u207b\u00b9',
ylabel: '',
def_station: '[WGL] ',
sel_station: '',
unit: ' m s\u207b\u00b9',
dp: 1
},
"dir": {
initgrid: 11,
title: '10-m Wind Direction',
domain: [0, 360],
intv: 90,
ylabel_unit: '',
ylabel: '',
def_station: '[WGL] ',
sel_station: '',
unit: '\u00b0',
dp: 1
}
}
let test = new ChartAction();
for(let obj in testData){
test.addRecord(new ChartData(...[obj, ...Object.values(testData[obj])]));
}
test.printGroup();