How to call backbone.model's this inside d3.drag context - javascript

I have the following backbone model with a d3.drag functionality. I cannot call the model's this inside the d3's context.
I came across with solutions for similar questions by defining a variable model=this and calling by model.draw.. but how can I add it inside d3's drag?
DataMapper.Models.Anchor = Backbone.Model.extend({
defaults: {
//...
},
initialize : function(){
d3.select("#anchor").call(this.dragAnchor); //make the #anchor draggable
},
dragAnchor: d3.drag()
.on("start", function (d) {
console.log("something"); //it prints
var thisDragY = this.drawSomething(a,b,c);
// this.drawSomething is not a function
// because inside d3.drag(), 'this' refers to #anchor
// what I want to refer is the model
})
.on("drag", function (d) {})
.on("end", function (d) {}),
drawSomething: function (parent, cx, cy) {
//code
}
});
Is there a way to use underscore's bind to achieve my desired goal? Link to a useful article.

The solution was found by a team member - to call the drag as a function.
DataMapper.Models.Anchor = Backbone.Model.extend({
defaults: {
//...
},
initialize : function(){
d3.select("#anchor").call(this.dragAnchor()); //make the #anchor draggable
},
dragAnchor: function(){
var self=this;
return d3.drag()
.on("start", function (d) {
console.log("something"); //it prints
var thisDragY = self.drawSomething(a,b,c);
})
.on("drag", function (d) {})
.on("end", function (d) {}),
drawSomething: function (parent, cx, cy) {
//code
}
});

Related

Double click event not working on D3 version 6.1

Converting a D3.js forcediagram from version 5 to 6.1, I write:
let drag = simulation => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event,d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event,d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
// release of fixed positions
function dblclick(d) {
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
.on("dblclick", dblclick);
However, I am getting the error on dblclick:
Uncaught (in promise) Error: unknown type: dblclick d3.min.js:2:9279
The code is copied from: https://observablehq.com/#d3/force-directed-graph?collection=#d3/d3-force. Only the dblclick is added. It is working in version 5, but as a separate function.
How can I add dblclick in version 6.1 of D3.js the correct way?
First, there is no "dblclick" typename for drag.on, which is not the same of selection.on. Hence your error:
Error: unknown type: dblclick
The only valid typenames are: "start", "drag" and "end". That said, your code should not work, be it v5 or v6.
The rest of this answer deals with another major problem with D3 v6:
As specified in the API, selection.on() in D3 version 6 passes the event as the first argument:
When a specified event is dispatched on a selected element, the specified listener will be evaluated for the element, being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget)
Therefore, your function should be:
function dblclick(_, d) {
d.fx = null;
d.fy = null;
}
Here, the _ is just a JavaScript convention telling us that the first parameter (the event) is never used.

Variable scope in d3 when callback is an event function

I know there are many questions here about how to globalize the scope of variables that have been updated inside a json callback function. And I have been trying to work off those examples for days now but I cant seem to work out how I can adapt that to my code when my json callbacks are on an event eg.on right click(context menu). I have been trying to use this example but have not been successful to try and adapt it to my code:
function myFunc(data) {
console.log(data);
}
d3.json('file.json', function (data) {
var json = data;
myFunc(json);
}
I am working with a scatterplot in d3. My first connection just adds two rows of my table into both of the arrays. Each row represents a dot. When I click on one of these dots, a connection is made to the database and links to that selected dot appear on the graph as other dots. And these are added to the baseData array and the libraryData remains the same. WHen I right click on one of these dots that dot is added to the libraryData array.But as indicated in the code, instances of libraryData outside of the function has not been updated. Below is my code
var libraryData = [];
var baseData = [];
d3.json("connection4.php", function(error,dataJson) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
libraryData.push(d);
baseData.push(d);
})
var circles = svg.selectAll("circle")
.data(libraryData) // libraryData here remains unchanged even after librayData has been updated in the function below!
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
.on("click", clickHandler)
function clickHandler (d, i) {
d3.json("connection2.php?paperID="+d.ID, function(error, dataJson) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
baseData.push(d);
})
var circles = svg.selectAll("circle")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill", "red")
.on("contextmenu", rightClickHandler);
})
function rightClickHandler (d, i) {
d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) {
})
d3.select(this)
.style("fill", "blue");
libraryData.push(d);
console.log(libraryData);// updated
}
console.log(libraryData)// not updated
});
I am new to d3 and I would appreciate any help and feedback thanks in advance!!
It's not scope, it's a timing issue
function rightClickHandler (d, i) {
d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) {
})
d3.select(this)
.style("fill", "blue");
libraryData.push(d);
console.log("I bet I'm second", libraryData);// updated
}
console.log("I bet I'm first", libraryData)// not updated
});
thefunction(error, dataJson) in the json call only executes once json is returned from your php function which can take a while. Meanwhile, your program performs the second call to console.log runs straight away and before the function in the json call has added anything to libraryData.
Run the above with the changes to console.log to see
Basically anything you want to do that depends on library data being updated must be called inside function(error, dataJson)

Fading/highlighting in D3 cluster force layout

I am working on this D3 force layout with clusters example:
I would like to highlight only nodes of the current cluster on mouse hovering a node (other clusters should fade to opacity 0.1).
What would be your approach?
I first wrote this function for comparison of two nodes' clusters:
function isSameCluster(a, b) {
return a.cluster == b.cluster;
};
Than, a function fade() that uses the function above: (it is meant to be called for any value of the argument "opacity")
function fade(opacity) {
return function(d) {
node.style("stroke-opacity", function(o) {
thisOpacity = isSameCluster(d, o) ? 1 : opacity;
this.setAttribute('fill-opacity', thisOpacity);
return thisOpacity;
});
};
};
After that, this is how I linked mouse hover and function fade():
.on("mouseover", fade(.1))
.on("mouseout", fade(1));
The result is this:

Simple function does not work within if-statement

I have a somewhat nested JSON file:
{
"name": "1370",
"children": [
{
"name": "Position X",
"value": -1
},
{...}
]
"matches": [
{
"certainty": 100,
"match": {
"name": "1370",
"children": [
{
"name": "Position X",
"value": -1
},
{...}
]
}
}
]
}
I want to display it using a modified Collapsible Tree. I want to display the "match" and "certainty" when hovering the corresponding node. I've used the simple tooltip example for this.
Now I have something like this:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) {
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( function(d) { return d.name; } );
}
} )
...
;
I'm just using d.name for testing. I want to write a more complex function later. But that doesn't work at all. I get a tooltip, but it's empty (or contains the default value). The point which I don't understand is, that the following works:
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( d.name );
}
Therefore it seems to me, that a function doesn't work at this point. What am I doing wrong?
The mistake you are making is that in your call to jQuery's .text() method, you are passing in a function, but what you want to pass in is the return value of that function. In order to do this, you simply need to invoke the function you are passing in with the argument it expects:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) {
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( function(d) { return d.name; }(d) );
}
} )
...
;
notice how the function is invoked using (d) after it is declared
The tooltip in the linked example does not have any data associated with it. Hence, if you try to use the text function with an accessor, it cannot get any data.
My guess is that you do not want to take data from the tooltip, but instead work with the data passed by D3 to your mouseover event:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) { // <-- This is the data passed by D3, associated to your node.
if (d.matches) {
var newName = computeNameFromData(d);
return tooltip.style("visibility", "visible")
.text( newName ); // <-- Just pass a string here.
}
} )
...
;

D3.js, Need click event in d3.js

I am trying to make a bubble chart, in that if i click on a bubble, the title of the bubble should appear in the console. I tried some ways, but was not successful.
d3.json("deaths.json",
function (jsondata) {
var deaths = jsondata.map(function(d) { return d.deaths; });
var infections = jsondata.map(function(d) { return d.infections; });
var country = jsondata.map(function(d) { return d.country; });
var death_rate = jsondata.map(function(d) { return d.death_rate; });
console.log(deaths);
console.log(death_rate);
console.log(infections);
console.log(country);
console.log(date);
//Making chart
for (var i=0;i<11;i++)
{
var f;
var countryname=new Array();
var dot = new Array();
dot = svg.append("g").append("circle").attr("class", "dot").attr("id",i)
.style("fill", function(d) { return colorScale(death_rate[i]); }).call(position);
//adding mouse listeners....
dot.on("click", click());
function click()
{
/***********************/
console.log(country); //i need the title of the circle to be printed
/*******************/
}
function position(dot)
{
dot .attr("cx", function(d) { return xScale(deaths[i]); })
.attr("cy", function(d) { return yScale(death_rate[i]); })
.attr("r", function(d) { return radiusScale(infections[i]); });
dot.append("title").text(country[i]);
}
}
});
I need the title of circle to be printed
Please help!!!
You had the good idea by using the on("click", ...) function. However I see two things:
The first problem is that you don't call the function on the click event but its value. So, you write dot.on("click", click()); instead of dot.on("click", click);. To understand the difference, let's imagine that the function click needs one argument, which would for example represent the interesting dot, what would it be? Well, you would write the following:
dot.on("click", function(d){click(d)})
Which is equivalent (and less prone to errors) to writing:
dot.on("click", click)
Now, the second point is that, indeed you want to pass the node as an argument of the function click. Fortunately, with the on event, as I used in my example, the function click is called with the argument d which represents the data of dot. Thus you can now write:
dot.on("click", click);
function click(d)
{
console.log(d.title); //considering dot has a title attribute
}
Note: you can also use another argument by writing function click(d,i) with i representing the index in the array, see the documentation for more details.
If you have a title on your data,
dot.on('click' , function(d){ console.log(d.title); });

Categories