Reputation: 28328
I'm having difficulties removing an event listener, since removeEventListener
only works for non-anynomous functions I need to make a named function. The problem is I can't figure out how to pass the chart
variable to the toggleLabels
function without calling the function while I do it..
I tried looking at this question but no answer worked.
Is this possible?
var chart = {}; // Big object
labelToggle.addEventListener('click', toggleLabels);
function toggleLabels(chart) {
scope.graph.isLabelsVisible = chart.isLabelsVisible = !chart.isLabelsVisible;
for (i = 0; i < length; i++) {
chart.series[i].isLabelsVisible = !chart.series[i].isLabelsVisible;
chart.series[i].hide();
chart.series[i].show();
};
};
Upvotes: 0
Views: 735
Reputation: 1867
Here the shortest solution:
labelToggle.addEventListener('click', function(){toggleLabels(chart)});
Upvotes: 0
Reputation: 7068
When passing parameters, you can use an "anonymous function" that calls the specified function with the parameters:
labelToggle.addEventListener("click", function() {
toggleLabels(chart);
});
var a = 5;
var b = 7;
document.getElementById('btn').addEventListener("click", function() {
myFunction(a, b);
});
function myFunction(x, y) {
var result = x + y;
console.log(result);
}
<button id="btn">Click here!</button>
Upvotes: 1
Reputation: 4201
It can be done by using partial application:
labelToggle.addEventListener('click', toggleLabels.bind(this,chart));
Upvotes: 0
Reputation: 7769
You can return a function like this:
var chart = {}; // Big object
labelToggle.addEventListener('click', toggleLabels(chart));
function toggleLabelsCls(chart) {
return function(chart) {
scope.graph.isLabelsVisible = chart.isLabelsVisible = !chart.isLabelsVisible;
for (i = 0; i < length; i++) {
chart.series[i].isLabelsVisible = !chart.series[i].isLabelsVisible;
chart.series[i].hide();
chart.series[i].show();
};
}
};
Upvotes: 0
Reputation: 18699
What you can do, is to make toggleLabels a function of chart. For example:
function chart(series) {
this.series = series;
this.toggleLabels = function (name) {
for (i = 0; i < lthis.series.ength; i++) {
chart.series[i].isLabelsVisible = !this.series[i].isLabelsVisible;
this.series[i].hide();
this.series[i].show();
};
};
}
And then just operate on the chart
object like this:
chart.series
chart.toggleLabels()
And then, you should be able to do the following:
labelToggle.addEventListener('click', chart.toggleLabels);
Upvotes: 0