AntoineLev AntoineLev - 2 months ago 6
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())
return
$('.nb_votes').each (i, obj) ->
poll_data.push($( obj ).text())
poll_colors.push('#' + Math.floor(Math.random() * 16777215).toString(16))
return
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))
this.pollPieChart.data.datasets[0].data[i] = data
this.pollPieChart.update()


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

Answer

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)