我有以下ES模块,用于初始化Google图表。
const ScreenB = () => ()
export default ScreenB;
mychart.js
let redraw;
function init(data) {
// Do stuff to populate the chart
// [...]
// Set the redraw function which will be called on resize
redraw = () => chart.draw(data, chartOptions);
redraw();
$(window).resize(redraw);
}
export default { redraw, init, [...] };
main.js
当我的网页显示时,图表可以工作,并且在import Mychart from './mychart';
$('#specific-button').on('click', function() {
$('#chart-container').toggle(function() {
// Also call redraw function when toggling HTML container visible
if ($('#chart-container').is(':visible')) {
Mychart.redraw();
}
});
});
$.ajax(/* Some ajax query */,
success: function(data) {
// First init of the Chart
Mychart.init(data);
}
);
事件中可以正确调整图表的大小。但是,当我单击window.resize
元素时,会抛出一个#specific-button
错误。解决该问题的方法是什么?
undefined
答案 0 :(得分:3)
从模块中导出对象时,redraw
的值为undefined
。稍后将不同的值分配给变量将不会更新该对象。简单的例子:
var foo;
var bar = {foo};
foo = 42;
console.log(bar);
您可以预先定义对象并更新对象:
const chart = {};
function init(data) {
// Do stuff to populate the chart
// [...]
// Set the redraw function which will be called on resize
chart.redraw = () => chart.draw(data, chartOptions);
chart.redraw();
$(window).resize(chart.redraw);
}
chart.init = init;
export default chart;
或者您也可以使用命名导出(“实时”绑定):
export let redraw;
export function init(data) {
// Do stuff to populate the chart
// [...]
// Set the redraw function which will be called on resize
redraw = () => chart.draw(data, chartOptions);
redraw();
$(window).resize(redraw);
}
在main.js
中:
import * as Mychart from './mychart';
话虽如此,一种更好的方法(在两种情况下)都是使用空函数初始化redraw
,以便它始终具有适当的值(直到图表初始化后它才做任何事情) )。