AntoineLev AntoineLev - 1 month ago 4
CoffeeScript Question

chart.js coffeescript can't find variable

I have this pie chart that displays correctly with the right data :

# setup the pieChart
if ($( "#pieChart" ).length)
poll_labels = []
poll_data = []
poll_colors = []
$('.option_text').each (i, obj) ->
poll_labels.push($( obj ).text())
$('.nb_votes').each (i, obj) ->
poll_data.push($( obj ).text())
poll_colors.push('#' + Math.floor(Math.random() * 16777215).toString(16))
data =
labels: poll_labels
datasets: [ {
data: poll_data
backgroundColor: poll_colors
hoverBackgroundColor: poll_colors
} ]

ctx = document.getElementById('pieChart')
pollPieChart = new Chart(ctx,
type: 'pie'
data: data
animation: animateRotate:true)

$('#pieChart').on 'data:update', (event, data_id, data) ->
$('.answer_option').each (i, obj) ->
if($( obj ).attr('id') == ("option_" + data_id))[0].data[i] = data

However, the
event can't find the pollPieChart variable to update it?
it's not in
, I can't find it under just
. Did the variable "disapear" after the new ?


pollPieChart is a local variable, not a property on the event's this context.

Inside the 'data:update' event listener, js automatically sets this to be the element on which the event occurred (document.getElementById('')).

Simply removing the this. from before pollPieChart inside the callback should fix it, as it is defined within the current closure, not the global window object.

To place it on the global window (though it's not necessary here),use

window.pollPieChart = new Chart(ctx,
  type: 'pie'
  data: data
  animation: animateRotate:true)