Ond*_*žka 1 encapsulation event-handling d3.js typescript angular
我在 Angular 2 组件中有一个 D3.js 代码,用 TypeScript 编写。
自然地,我倾向于以 OOP 方式包装东西,以便组件可以(例如)多次重用。
但是,我在将某些内容传递给事件处理程序时遇到了问题。
this.simulation = d3.forceSimulation()
...
.on("tick", this.onSimulationTick);
Run Code Online (Sandbox Code Playgroud)
onSimulationTick()只能访问全局变量,d3.event并且this:
当指定的事件被调度时,每个监听器都会以 this 上下文作为模拟被调用。
全局变量不是一个选项,破坏了封装。我无法将任何内容附加到d3.event,而且我不知道它们的上下文是什么意思。
在处理程序中,我想访问一些属于类成员的东西。所以最好是传递组件对象。
我怎样才能将任何东西传递给处理程序?我怎么能使用它的上下文?
也许我可以以某种方式使用 lambda,比如
.on("tick", () => onSimulationTick.that = this, onSimulationTick );
Run Code Online (Sandbox Code Playgroud)
这是缩短的组件代码:
@Component({
templateUrl: "dependencies-graph.component.html",
styleUrls: ["dependencies-graph.component.css"],
selector: 'wu-dependencies-graph',
})
export class DependenciesGraphComponent implements OnInit, OnChanges {
// Data
_dependencies: DependenciesData;
private jsonData;
// Selections
private zoomingGroup;
// Behaviors
private simulation;
private zoom;
private center: Point;
private initVisualisation() {
this.zoomingGroup = d3.select("svg #zoomingGroup");
...
this.simulation = d3.forceSimulation()
...
.on("tick", this.onSimulationTick);
}
static onSimulationTick() {
???.zoomingGroup.selectAll(".myEdge")
.attr("x1", function(item) { return item.source.x; })
.attr("y1", function(item) { return item.source.y; })
.attr("x2", function(item) { return item.target.x; })
.attr("y2", function(item) { return item.target.y; });
???.zoomingGroup.selectAll(".myGroup")
.attr("transform", function(d){return "translate("+d.x+","+d.y+")"});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Function.prototype.bind方法绑定上下文:
private initVisualisation() {
this.zoomingGroup = d3.select("svg #zoomingGroup");
...
this.simulation = d3.forceSimulation()
...
.on("tick", this.onSimulationTick.bind(this));
}
static onSimulationTick() {
this.zoomingGroup.selectAll(".myEdge")
.attr("x1", function(item) { return item.source.x; })
.attr("y1", function(item) { return item.source.y; })
.attr("x2", function(item) { return item.target.x; })
.attr("y2", function(item) { return item.target.y; });
this.zoomingGroup.selectAll(".myGroup")
.attr("transform", function(d){return "translate("+d.x+","+d.y+")"});
}
Run Code Online (Sandbox Code Playgroud)
如果你想传递额外的参数箭头函数可能是更好的选择:
.on("tick", () => this.onSimulationTick(somethingElse));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1621 次 |
| 最近记录: |