I have the following code for a drag event:
我有以下拖动事件的代码:
BusinessProductFigure.prototype = new Figure();
BusinessProductFigure.prototype.constructor = BusinessProductFigure;
BusinessProductFigure.prototype.addTo = function(c, x0, y0, id) {
console.log("this=",this);
var n = d3.select(this);
var wasMoved = false;
var dragger = d3.behavior.drag()
.origin(function(d){return d;})
.on("drag", this.move)
.on("dragend", dropHandler)
The function this.move executes in the above code and performs it's designated function. However, I want to add a function that is called upon on drag event. I tried the following:
这个函数。move在上面的代码中执行并执行指定的功能。但是,我想添加一个在拖动事件上调用的函数。我试着以下:
BusinessProductFigure.prototype.addTo = function(c, x0, y0, id) {
console.log("this=",this);
var n = d3.select(this);
var wasMoved = false;
var dragger = d3.behavior.drag()
.origin(function(d){return d;})
.on("drag", function(){wasMoved=true; this.move})
.on("dragend", dropHandler)
But the above code does not calls the move function. How can I access 'this' property inside the function?
但是上面的代码不调用move函数。如何访问函数中的“this”属性?
2 个解决方案
#1
2
You can bind relevant context using bind()
, and use parenthensis to call the method:
您可以使用bind()绑定相关上下文,并使用括号调用方法:
.on("drag", function(){wasMoved=true; this.move()}.bind(this))
内(“拖”,函数(){ wasMoved = true;this.move()} .bind(这))
#2
1
Another solution because it's 2016 already is to use arrow function to preserve lexical context:
由于2016年已经到来,另一个解决方案是使用箭头函数来保存词汇上下文:
.on("drag", () => {
wasMoved = true;
this.move()
})
#1
2
You can bind relevant context using bind()
, and use parenthensis to call the method:
您可以使用bind()绑定相关上下文,并使用括号调用方法:
.on("drag", function(){wasMoved=true; this.move()}.bind(this))
内(“拖”,函数(){ wasMoved = true;this.move()} .bind(这))
#2
1
Another solution because it's 2016 already is to use arrow function to preserve lexical context:
由于2016年已经到来,另一个解决方案是使用箭头函数来保存词汇上下文:
.on("drag", () => {
wasMoved = true;
this.move()
})