Crea una variabile per i testi e spostala fuori dal socket
:
d3.json("india-states.json", function (json) {
india.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path);
var stateText = india.selectAll(".text")
.data(json.features)
.enter()
.append("text");//variable outside socket
var socket = io();
socket.on('tags', function(data){
stateText.attr("fill", "black")
.attr("transform", function(d) {
console.log(data.message1 + "Second Time");
var centroid = path.centroid(d);
return "translate(" + centroid[0] + "," + centroid[1] + ")"
})
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.style('fill', 'white')
.text(function(d) {
if (d.id == data.message1) {
return data.message1;
}
});
});
});
Se vuoi tenere traccia del tuo message1
precedente , puoi creare un array al di fuori della funzione e scorrerlo:
d3.json("india-states.json", function (json) {
india.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path);
var stateText = india.selectAll(".text")
.data(json.features)
.enter()
.append("text");
var arrayStates = [];//this array will hold all the names
var socket = io();
socket.on('tags', function(data){
arrayStates.push(data.message1);//for each input, a new string
stateText.attr("fill", "black")
.attr("transform", function(d) {
var centroid = path.centroid(d);
return "translate(" + centroid[0] + "," + centroid[1] + ")"
})
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.style('fill', 'white')
.text(function(d) {
for(var i = 0; i < arrayStates.length; i++){
if (d.id == arrayStates[i]) {
return arrayStates[i];
}
}
});
});
});