Reputation: 822
I "warp" d3 drag code inside class and have a problem with this
when I try to use class fields in different class methods.
Here a code:
'use strict';
class D3DragHandler {
constructor(link, datas) {
this.drag = null;
this.links = link;
this.datas = datas;
this.zadragged = null;
// console.log(this.link);
}
saveNodePosition() {
var postData = {};
var adragged = this.zadragged; //ERROR HERE
postData.id = datas[adragged].id;
postData.x = datas[adragged].dx + datas[adragged].x;
postData.y = datas[adragged].dy + datas[adragged].y;
d3.xhr('/index.php?option=com_myrod&task=ajax.save&format=json&raw=true&token=' + token + "&data=" + JSON.stringify({
"data": postData
}))
.header("Content-Type", "application/json")
.post("",
function (err, rawData) {
var data = JSON.parse(rawData);
console.log("got response", data);
});
}
setDragged(value) {
console.log(value);
this.zadragged = value; //ERROR HERE
//var v = this.zadragged;
}
init() {
var link = this.links;
var datas = this.datas;
var saveFunc = this.saveNodePosition;
var draggedKeyFunc = this.setDragged;
// Define drag beavior
this.drag = d3.behavior.drag()
.on("drag", function (d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
//adragged = d.key;
draggedKeyFunc(d.key);
datas[d.key].dx = d3.event.x;
datas[d.key].dy = d3.event.y;
link.update();
})
.origin(function () {
var t = d3.transform(d3.select(this).attr("transform"));
svg.select("text.position").text(function (d) {
return Math.round(d.value.x) + ":" + Math.round(d.value.y);
})
return {
x: t.translate[0],
y: t.translate[1]
};
})
.on("dragend", function () {
var d = d3.event.sourceEvent;
console.log(d);
saveFunc(d);
});
return this.drag;
}
}
I make comments in code to show where I get errors, and it is very strange, because I use this
in other methods and it works just fine. But in this strings I get error:
TypeError: this is undefined
It is very strange, I expect that all code must work same way, but maybe I did miss something here?
setDragged(value)
method is class method so i expect that this
is class itself.
Upvotes: 1
Views: 78
Reputation:
You can use class property like below, if you include babel plugin in your build process
setDragged = (value) => {
console.log(value);
this.zadragged = value; //ERROR HERE
}
Upvotes: 0
Reputation: 60527
Your problem is that class methods are not bound to any specific object, so this
refers to whatever object they were called as a method of, so when you this:
var draggedKeyFunc = this.setDragged;
// ...
draggedKeyFunc(d.key);
That object association is gone, and this
is undefined
in strict mode, or the global object outside of strict mode.
Options include calling the object as a method:
var dragHandler = this;
// ...
dragHandler.draggedKeyFunc(d.key);
Or creating a bound function:
var draggedKeyFunc = this.setDragged.bind(this);
// ...
draggedKeyFunc(d.key);
Upvotes: 4