chart.js coffeescript 找不到变量
chart.js coffeescript can't find variable
我有这个饼图,可以正确显示正确的数据:
# 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()
但是data:update
事件找不到pollPieChart变量来更新?
它不在 window.pollPieChart
中,我在 pollPieChart
下找不到它。新的变量"disapear"之后有没有?
pollPieChart
是局部变量,而不是事件 this
上下文中的 属性。
在'data:update'
事件监听器中,js自动设置this
为事件发生的元素(document.getElementById('')
)。
只需删除回调中 pollPieChart
之前的 this.
即可修复它,因为它是在 current closure 中定义的,而不是全局 window
对象。
要将它放在全局 window 上(虽然这里没有必要),请使用
window.pollPieChart = new Chart(ctx,
type: 'pie'
data: data
animation: animateRotate:true)
我有这个饼图,可以正确显示正确的数据:
# 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()
但是data:update
事件找不到pollPieChart变量来更新?
它不在 window.pollPieChart
中,我在 pollPieChart
下找不到它。新的变量"disapear"之后有没有?
pollPieChart
是局部变量,而不是事件 this
上下文中的 属性。
在'data:update'
事件监听器中,js自动设置this
为事件发生的元素(document.getElementById('')
)。
只需删除回调中 pollPieChart
之前的 this.
即可修复它,因为它是在 current closure 中定义的,而不是全局 window
对象。
要将它放在全局 window 上(虽然这里没有必要),请使用
window.pollPieChart = new Chart(ctx,
type: 'pie'
data: data
animation: animateRotate:true)