Function D3.js brushend函数未正确调用
我制作了一个模块,用于绘制条形图,包括Function D3.js brushend函数未正确调用,function,d3.js,this,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
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.*
值,我不能使用function brushend()
或var brushend=function()
将brushend
函数设置为正常函数
如何正确地调用它?D3将调用为其
brushend
事件提供的事件处理程序,就像调用普通DOM事件的事件处理程序一样。对于标准事件,此
将引用事件发生时的元素。此规则也适用于D3的笔刷事件处理程序,此
引用包含笔刷DOM元素的组。显然,此组没有属性brush
,您可以使用处理程序中的this.brush
进行引用
解决方法是使用以下命令保存引用:
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);
};
}