gpt4 book ai didi

javascript - Chart.js CoffeeScript 找不到变量

转载 作者:行者123 更新时间:2023-11-27 22:32:06 24 4
gpt4 key购买 nike

我有这个饼图,可以正确显示正确的数据:

  # 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 下找不到它。变量在 new 之后“消失”了吗?

最佳答案

pollPieChart 是一个局部变量,而不是事件的 this 上下文中的属性。

'data:update'事件监听器中,js自动将this设置为发生事件的元素(document.getElementById('' ))。

只需从回调内的 pollPieChart 之前删除 this. 即可修复该问题,因为它是在 current closure 中定义的。 ,而不是全局 window 对象。

要将其放置在全局窗口上(尽管这里没有必要),请使用

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

关于javascript - Chart.js CoffeeScript 找不到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39474823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com