点击SVG Renderer按钮调用ping_device函数时提示“this.ping_device不是函数”
问题解决:this.ping_device is not a function
问题核心是按钮点击回调里的this指向错误——按钮的点击回调函数中,this默认指向SVG按钮元素本身,而非你定义ping_device方法的对象,所以找不到该函数。以下是几种修复方案:
方案1:提前保存正确上下文
在外部click事件里先存储正确的this指向,后续在按钮回调中使用:
events: { click: function(event) { debugger console.log(event); var point = this, chart = this.chart; // 保存包含ping_device方法的对象上下文 var self = this; if (chart.customTooltip) { chart.customTooltip.destroy(); chart.customTooltip = undefined; } chart.customTooltip = chart.renderer.button( 'Ping', chart.plotLeft + event.point.plotX, chart.plotTop + event.point.plotY - 80, function() { debugger // 使用提前保存的self调用方法 self.ping_device(event.point.id.trim()); } ).attr({ 'stroke-width': 1, zIndex: 8, stroke: 'red', padding: 8, r: 3, fill: 'rgb(247, 247, 247)' }).add(); chart.rGroup.translate(-chart.customTooltip.width / 2, -chart.customTooltip.height + 40).toFront() } } ping_device(device) { // 此处编写你的业务逻辑 console.log(device); }
方案2:使用ES6箭头函数
箭头函数不会绑定自身this,会继承外层作用域的this,代码更简洁:
events: { click: function(event) { debugger console.log(event); var point = this, chart = this.chart; if (chart.customTooltip) { chart.customTooltip.destroy(); chart.customTooltip = undefined; } chart.customTooltip = chart.renderer.button( 'Ping', chart.plotLeft + event.point.plotX, chart.plotTop + event.point.plotY - 80, // 替换为箭头函数,直接沿用外层this () => { debugger this.ping_device(event.point.id.trim()); } ).attr({ 'stroke-width': 1, zIndex: 8, stroke: 'red', padding: 8, r: 3, fill: 'rgb(247, 247, 247)' }).add(); chart.rGroup.translate(-chart.customTooltip.width / 2, -chart.customTooltip.height + 40).toFront() } } ping_device(device) { // 此处编写你的业务逻辑 console.log(device); }
方案3:用bind绑定this
手动将回调函数的this绑定到外部正确上下文:
events: { click: function(event) { debugger console.log(event); var point = this, chart = this.chart; if (chart.customTooltip) { chart.customTooltip.destroy(); chart.customTooltip = undefined; } // 定义回调并绑定正确的this const handlePing = function() { debugger this.ping_device(event.point.id.trim()); }.bind(this); chart.customTooltip = chart.renderer.button( 'Ping', chart.plotLeft + event.point.plotX, chart.plotTop + event.point.plotY - 80, handlePing ).attr({ 'stroke-width': 1, zIndex: 8, stroke: 'red', padding: 8, r: 3, fill: 'rgb(247, 247, 247)' }).add(); chart.rGroup.translate(-chart.customTooltip.width / 2, -chart.customTooltip.height + 40).toFront() } } ping_device(device) { // 此处编写你的业务逻辑 console.log(device); }
三种方案任选其一即可解决问题,推荐方案2,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者yashwardhan
相关产品推荐
相关产品推荐

