例如,我正在使用 D3.js 运行一个项目,导入特定模块并调用它们的函数。
Setup:
- TypeScript/ES6
- 导入特定的 D3 组件
- 角6
我有一个对象(在本例中是一个角度指令),并在 SVG 画布上绘制一些圆圈,并希望它们在拖动事件上触发函数。
减少的代码片段: 请看一下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 https://bl.ocks.org/mbostock/22994cc97fefaeede0d861e6815a847e