小编gro*_*sNL的帖子

与 d3 事件绑定

在 d3 中编写事件处理程序时,有没有办法bind直接使用等效项?我bind在文档中的任何地方都没有看到实施或讨论。

目前我正在这样做:

graph = function () {
    var self = this;
    this.svg = d3.select('body').append('svg');
    this.svg.append('svg:rect')
        .style('fill', '#f00')
        .attr('width', 300)
        .attr('height', 300);
    this.svg.on('mousedown', function(){return self.mouseDown.call(this, self);})
}
graph.prototype.mouseDown = function (self) {
    /* 'self' is the instance of graph */
    alert(self.svg);
    /* 'this' is the event */
    alert(d3.mouse(this));
}
var g = new graph();
Run Code Online (Sandbox Code Playgroud)

JSFiddle

这工作正常。然而,在这里使用匿名函数call似乎是不好的做法,因为bind本来可以在常规 DOM 元素上完成此操作(如果我没有使用 d3 选择)。我更喜欢使用 d3 选择而不是针对底层 DOM 元素(为了一致性,因为this.svg已经附加到graph对象)。

由于 d3 的 …

javascript svg d3.js

4
推荐指数
1
解决办法
2092
查看次数

标签 统计

d3.js ×1

javascript ×1

svg ×1