I have some buttons that I make visible at the time I make my graph visible.
I also put a line through the text depending on the dataset visibility status.
Is there a way to pass an argument to the jquery $()
so that I can handle this logix in a neat for
loop?
if (!this.drawnAlready) {
//button subscription
$('#ds0').css("visibility", "visible");
$('#ds0').click( function(){
chartTest.data.datasets[0].hidden = !chartTest.data.datasets[0].hidden;
chartTest.update();
$('#ds0').css("text-decoration", chartTest.data.datasets[0].hidden ? "line-through" : "none");
});
$('#ds1').css("visibility", "visible");
$('#ds1').click( function(){
chartTest.data.datasets[1].hidden = !chartTest.data.datasets[1].hidden;
chartTest.update();
$('#ds1').css("text-decoration", chartTest.data.datasets[1].hidden ? "line-through" : "none");
});
$('#ds2').css("visibility", "visible");
$('#ds2').click( function(){
chartTest.data.datasets[2].hidden = !chartTest.data.datasets[2].hidden;
chartTest.update();
$('#ds1').css("text-decoration", chartTest.data.datasets[2].hidden ? "line-through" : "none");
});
$('#ds3').css("visibility", "visible");
$('#ds3').click( function(){
chartTest.data.datasets[3].hidden = !chartTest.data.datasets[3].hidden;
chartTest.update();
$('#ds3').css("text-decoration", chartTest.data.datasets[3].hidden ? "line-through" : "none");
});
}
In the example I show that I do it for three buttons for code clarity, but in my code there are quite a lot of buttons so the code seems clearly improvable :).
CodePudding user response:
Give all your #ds0/#ds1/etc the same class="ds"
, also give them a data-datasetid="0"
to replace the #ds0 etc
<button class="ds" data-datasetid="0">toggle data set 0</button>
<button class="ds" data-datasetid="1">toggle data set 1</button>
then replace your code with:
if (!this.drawnAlready) {
$('.ds').css("visibility", "visible");
$('.ds').click(function() {
var dataset = $(this).data("datasetid");
chartTest.data.datasets[dataset].hidden = !chartTest.data.datasets[dataset].hidden;
chartTest.update();
$(this).css("text-decoration", chartTest.data.datasets[dataset].hidden ? "line-through" : "none");
});
}
CodePudding user response:
You are repeating code. So, just write a method that does the repeating part of your code.
For example:
function doThings(i)
{
const elementId = '#ds' i;
$(elementId).css("visibility", "visible");
$(elementId).click( function(){
chartTest.data.datasets[i].hidden = !chartTest.data.datasets[i].hidden;
chartTest.update();
$(elementId).css("text-decoration", chartTest.data.datasets[i].hidden ? "line-through" : "none");
});
}
Then you just need to call this function multiple times. For example:
[1, 2, 3, 4, 5].forEach( i => doThings(i))