D3.js brushend功能没有正确调用

时间:2015-12-03 00:21:28

标签: function d3.js this

我制作了一个绘制包含d3.svg.brush()条形图的模块。我的部分代码是

Bar.prototype.init = function ( ) {
     //...
     this.brush = d3.svg.brush()
                     .y( this.y)
                     .on("brushend", this.brushend);
     console.log(this.brushend); // works
} 
Bar.prototype.brushend = function() {
    console.log(this.brush); // undefined. why?
}

要访问this.*值,我无法使用brushendfunction brushend()使var brushend = function()功能成为正常功能。

我该怎么称呼它?

1 个答案:

答案 0 :(得分:0)

D3将调用为其brushend事件提供的事件处理程序,就像调用普通DOM事件的事件处理程序一样。对于标准事件,this将引用事件发生的元素。此规则也适用于D3的画笔事件处理程序,其中this引用包含画笔的DOM元素的组。显然,这个组没有可以通过处理程序使用brush来引用的属性this.brush

解决方法是使用closure保存您的引用:

Bar.prototype.init = function ( ) {
     //...
     this.brush = d3.svg.brush()
                     .y(this.y)
                     .on("brushend", this.brushend());  // Get handler by calling factory
}

// A factory returning the handler function while saving 'this'. 
Bar.prototype.brushend = function() {
    var self = this;      // Save a reference to the real 'this' when the factory is called.
    return function() {   // Return the handler itself.
         // By referencing 'self' the function has access to the preserved
         // value of 'this' when the handler is called later on.
        console.log(self.brush);
    };
}