我正在使用 Backbone.js,并且有四个模板可以显示 4 个图表。一切工作正常,但唯一的问题是我的页面在所有图形呈现在 UI 上之前刷新了四次。页面刷新速度非常快。在页面/图表开始显示之前,chrome 的刷新图标会超快地闪烁。
我使用 jquery 的 when then
来确保在 View 开始渲染之前完全获取我的模型。另外,我为图形的所有 View 模型调用了四次 this.render()
。这显然是需要的,因为我有四个模板。有人可以指导我可能出现什么问题吗?
first viewmodel:
initialize: function() {
this.model.on('change', this.render, this);
this.render();
}
所有四个 View 模型都会重复同样的事情。
一张图的实际 View 模型:
define(['backbone'], function(Backbone) {
var firstSubViewModel = Backbone.View.extend({
template: _.template($('#myChart-template').html()),
/**
* render function. Renders data onto graph.
* @param none
*/
render: function() {
console.log("inside first sub view render");
$(this.el).html(this.template());
var ctx = $(this.el).find('#lineChart')[0];
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "This Year",
backgroundColor: "rgba(38, 185, 154, 0.31)",
data: this.model.attributes.incThisYear
}, {
label: "Last Year",
backgroundColor: "rgba(3, 88, 106, 0.3)",
borderColor: "rgba(3, 88, 106, 0.70)",
data: this.model.attributes.incLastYear
}]
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Income in $'
}
}]
}
}
});
},
initialize: function() {
console.log("inside first sub view initialize");
this.model.on('change', this.render, this);
this.render();
}
});
return firstSubViewModel;
});
最佳答案
这有点盲目,但我相信问题在于您首先添加偶数监听器 (this.model.on('change', this.render, this);
),然后当您实际调用 render()
时,它会检测到更改,从而再次触发 render()
。
只需尝试翻转它们即可:
initialize: function() {
this.render(); // render it first
this.model.on('change', this.render, this);
}
关于javascript - 页面呈现正确,但刷新多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532711/