![](/img/trans.png)
[英]how to call a different methods from JavaScript file in rails controller method
[英]How to call class method in different javascript file?
此 class 包含在外部文件名graph.js
中。 我正在嘗試從其class graphElement
drawchart
方法繪制圖。 該文件包含在 html 腳本 src 中。 我什至可以毫無問題地調用function fetchYearly()
但class method keeps throwing error
。 我正在使用庫chart.js
。
這是我的代碼:
class graphElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = document.querySelector('#tmpGraph').innerHTML;
let canvas1 = document.getElementById('graph').shadowRoot.querySelector('#myChart'); let transType = ['Debit', 'Credit'];
fetchYearlyData('CREDIT');
fetchYearlyData('DEBIT');
this.drawChart(transType);
}
drawChart(transType) {
var ctx = document.getElementById('graph').shadowRoot.querySelector('#myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: transType[0],
borderColor: "#f48480",
pointBorderColor: "#f48480",
pointBackgroundColor: "#f48480",
pointHoverBackgroundColor: "#f48480",
pointHoverBorderColor: "#f48480",
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: false,
borderWidth: 4,
data: dataDB
},
{
label: transType[1],
borderColor: "#80b6f4",
pointBorderColor: "#80b6f4",
pointBackgroundColor: "#80b6f4",
pointHoverBackgroundColor: "#80b6f4",
pointHoverBorderColor: "#80b6f4",
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: false,
borderWidth: 4,
data: dataCRD
}],
},
options: {
legend: {
position: "top"
},
scales: {
yAxes: [{
ticks: {
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
padding: 20,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
}
}
});
}
}
function fetchYearlyData(transType) {
//does some important stuff :)
}
我想在單擊時在另一個文件中調用 function drawchart()
。 它包含在 html 文件的腳本源中,但拋出: Uncaught (in promise) ReferenceError: drawChart is not defined error
,但是 function fetchYearly()
工作得很好。 我究竟做錯了什么?
fetchYearly
是 function。 drawChart
不是:它是 class graphElement
的實例方法。 您需要實例化一個graphElement
並在其上調用drawChart
。 它可能看起來像
let graph = new graphElement();
graph.drawChart();
這個graphElement
class 是 web 組件,所以如果你的圖表元素已經在屏幕上可見,你需要在 DOM 樹中找到它,但你需要向我們展示更多代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.