【发布时间】:2018-10-23 11:53:07
【问题描述】:
例如,我正在使用 D3.js 运行一个项目,导入特定模块并调用它们的功能。
设置:
- TypeScript/ES6
- 导入特定的 D3 组件
- 角度 6
我有一个对象,在这种情况下是一个角度指令,并在 SVG 画布上绘制了一些圆圈,并希望它们在拖动事件上触发一个函数。
缩码sn-p: 请看一下这个sn-p底部的drawPoints()
import { ElementRef, HostListener, Output, EventEmitter, OnInit, Input, OnChanges, SimpleChanges, Directive } from '@angular/core';
import * as Selection from 'd3-selection';
import * as Shape from 'd3-shape';
import * as Random from 'd3-random';
import * as Drag from 'd3-drag';
import { Config } from './../models/config.model';
import { Point } from './../models/point.model';
import { Param } from './../models/param.model';
@Directive({
selector: '[appCanvas]'
})
export class CanvasDirective implements OnInit, OnChanges {
private canvas: any;
private defs: any;
private gradient: any;
private svg: any;
private expandedPoints: Point[];
private drag: Point;
public config: Config;
@Input()
private param: Param;
@Output()
private emitConfig: EventEmitter<Config>;
@HostListener('window:resize', ['$event'])
private onResize(event) {
this.init();
}
constructor(
private el: ElementRef
) {
this.canvas = el.nativeElement;
this.emitConfig = new EventEmitter();
}
ngOnInit() {
intSvg();
// ..
}
private initSvg() {
if (!this.svg) {
this.svg = Selection.select(this.canvas).append('svg');
}
this.svg
.attr('width', this.config.width)
.attr('height', this.config.height);
}
private drawPoints(points: Point[]) {
points.forEach(point => {
this.svg.append('circle')
.attr('r', point.color ? 20 : 10)
.attr('cx', point.x)
.attr('cy', point.y)
.attr('fill', point.color ? point.color : 'lightgray')
.attr('stroke-width', !point.color ? 2 : 0)
.attr('stroke', !point.color ? 'gray' : '')
.call(Drag.drag()
.on('drag', () => {
// What to call here?
// Selection.select(this) will not work
// So how to target the correct „this“?
}));
});
}
// ...
}
出现的问题是无法在附加圆圈的拖动功能内到达正确的this。
有多个示例,但它们在类中不起作用,因为 this 参数受到保护。
感谢 Mike Bostock 的示例https://bl.ocks.org/mbostock/22994cc97fefaeede0d861e6815a847e
【问题讨论】:
标签: javascript typescript d3.js ecmascript-6 arrow-functions