[英]resolving scope of private method call within a function in another private method for typescript
Framework: Angular 5.x 框架: Angular 5.x
Structure is as follows: 结构如下:
ngAfterViewInit() {
// ... Some svg rendering code
function dblclick(d) {
d3.select(this).select('circle').transition()
.duration(1000)
.attr('r', 14);
this.makeJsonBackEnd(d); // in the browser console this is not a function error
}
}
makeJsonBackEnd(node) {
// extract info from d3 node to make a JSON for backend
}
I think because of the function
within the ngAfterViewInit()
the scope of the Component class is messed up and this
is not recognized. 我认为由于
ngAfterViewInit()
中的function
,Component类的范围被弄乱了, this
无法识别。
How can I call makeJsonBackEnd()
within the dblclick()
? 如何在
makeJsonBackEnd()
调用makeJsonBackEnd()
dblclick()
?
I tried making dblclick
a private method for the class but the this
call within d3.select(this)
won't get recognized 我试图使
dblclick
该类的私有方法,但this
内调用d3.select(this)
不会得到认可
Use a closure. 使用闭包。
ngAfterViewInit() {
const self = this;
// ... Some svg rendering code
function dblclick(d) {
d3.select(this).select('circle').transition()
.duration(1000)
.attr('r', 14);
self.makeJsonBackEnd(d); // in the browser console this is not a function error
}
}
makeJsonBackEnd(node) {
// extract info from d3 node to make a JSON for backend
}
You could try turning dblclick method into Arrow function like below 您可以尝试将dblclick方法转换为如下所示的Arrow函数
dblclick = d => { .... };
or the traditional way of holding this scope into local var. 或将这种范围保存在本地变量中的传统方法。
let me = this
, and call the method with me.makeJsonBackEnd(d)
like below let me = this
,并使用me.makeJsonBackEnd(d)
调用方法,如下所示
ngAfterViewInit() {
let me = this;
function dblclick(d) {
...
me.makeJsonBackEnd(d)
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.