我想知道我的方法对于这种情况是否有效/最佳实践: 我在 Angular 工厂中构造了一个像这样的标记。我没有扩展每种类型的标记,而是使用 switch 语句来切换标记的类型。类型决定了标记的图标。
engine.factory('marker', ['map', function (map) {
return function constructMarker(position, id, type) {
this.id = id;
this.position = position;
switch (type) {
case 'assigned':
this.icon = greenMarker;
break;
case 'unassigned':
this.icon = redMarker;
break;
default:
throw new Error(type + 'is an invalid marker type');
break;
}
return L.marker(this.position, {icon: this.icon}).addTo(map.layers[type]);
};
}]);
谢谢
最佳答案
这个更优雅一点:
engine.factory('marker', ['map', function (map) {
return function constructMarker(position, id, type) {
var types = {
'assygned':{
icon: greenMarker
},
'unassigned':{
icon: redMarker
}
}
if(!types[type]){
throw new Error(type + 'is an invalid marker type');
}
this.id = id;
this.position = position;
return L.marker(this.position, {icon: types[type].icon}).addTo(map.layers[type]);
};
}]);
关于JavaScript 约定 : switch statement in object constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22269359/