I am building a d3js based javascript frontpage. Whilst restructuring some code from functional to OOP the click method stopped being able to find the update method. I get Uncaught ReferenceError: this.update is not defined. I think its something to do with scope but im quite new to js so its hard for em to figure it out, any ideas?
class UpdateTree{
update(source){}
enter_new_nodes_at_the_parents_previous_position(node, source){
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) { return "translate(" source.y0 "," source.x0 ")"; })
.on("click", this.click);
}
click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
this.update(d);
}
}
CodePudding user response:
You should bind click
function with this
.
class UpdateTree{
update(source){}
enter_new_nodes_at_the_parents_previous_position(node, source){
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) { return "translate(" source.y0 "," source.x0 ")"; })
.on("click", this.click.bind(this));
}
click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
this.update(d);
}
}
CodePudding user response:
Reading more into this problem myself I have found that whilst javascript can be both functional and object orientated, d3js is (says this on their wiki) based around functional programming, therefore it seems to be a mistake to try an make it OOP.