如何编写可在多vehicle对象间复用的Leaflet popup动态文本模板
实现方案
方案1:封装通用模板生成函数(最推荐)
直接将重复的模板逻辑抽成独立函数,接收车辆对象作为入参,返回拼接完成的popup内容:
// 通用popup内容生成函数 function generateVehiclePopup(vehicle) { return ` <font size="4"><b>${vehicle.name}</b></font> <br>Plates number: ${vehicle.platesNumber} <br>Side number: ${vehicle.sideNumber} <br>Vehicle color: ${vehicle.color} <br>Type of vehicle: ${vehicle.type} <br><b>Vehicle range in km: ${vehicle.rangeKm}</b> <br><b>Battery level: ${vehicle.batteryLevelPct}%</b> <br><b>Reservation ends in: ${vehicle.reservationEnd}</b> <br><b>Vehicle is reserved by: ${vehicle.reservation}</b> <br><b>Status of car: ${vehicle.status}</b> <br><b>Location: ${vehicle.locationDescription}</b> <br>Current promotions: ${vehicle.promotion} <br>Description of the vehicle: ${vehicle.description} <br>Metadata of the vehicle: ${vehicle.metadata} <br>ID of the vehicle: ${vehicle.metadata}`; }
调用方式非常简单,需要生成哪个车辆的popup就把对应对象传进去即可:
// 生成vehicle1的popup内容 const popupContent1 = generateVehiclePopup(vehicle1); // 生成vehicle2的popup内容 const popupContent2 = generateVehiclePopup(vehicle2);
方案2:给车辆对象挂载内置方法
如果想要直接通过对象自身调用获取popup内容,可以给对象添加普通函数类型的方法(注意不要用箭头函数,否则this指向会异常,也就是你之前用this失败的常见原因):
// 示例:给vehicle1添加方法 const vehicle1 = { name: "示例车辆1", platesNumber: "京A12345", // 其余属性省略 getPopup() { return ` <font size="4"><b>${this.name}</b></font> <br>Plates number: ${this.platesNumber} <br>Side number: ${this.sideNumber} <br>Vehicle color: ${this.color} <br>Type of vehicle: ${this.type} <br><b>Vehicle range in km: ${this.rangeKm}</b> <br><b>Battery level: ${this.batteryLevelPct}%</b> <br><b>Reservation ends in: ${this.reservationEnd}</b> <br><b>Vehicle is reserved by: ${this.reservation}</b> <br><b>Status of car: ${this.status}</b> <br><b>Location: ${this.locationDescription}</b> <br>Current promotions: ${this.promotion} <br>Description of the vehicle: ${this.description} <br>Metadata of the vehicle: ${this.metadata} <br>ID of the vehicle: ${this.metadata}`; } } // vehicle2同理添加相同方法即可
调用时直接执行对应方法:
const popupContent1 = vehicle1.getPopup(); const popupContent2 = vehicle2.getPopup();
如果车辆对象是通过构造函数生成的,也可以把方法挂载到原型上,避免每个实例重复定义方法:
function Vehicle(attrs) { Object.assign(this, attrs); } Vehicle.prototype.getPopup = function() { // 同上模板内容,用this访问属性 } // 生成实例 const vehicle1 = new Vehicle({name: "车辆1", /* 其余属性 */}); const vehicle2 = new Vehicle({name: "车辆2", /* 其余属性 */});
内容的提问来源于stack exchange,提问作者CoCoJumbo
相关产品推荐
相关产品推荐

