看哪,主干 View 渲染调用:
render: function() {
$(this.el).html(this.template({title: 'test'})); //#1
this.renderScatterChart();
return this;
},
所以,我将标准渲染称为#1。然后,我调用一个方法 [这次,它是图表库的包装器] 来查找 div。 div 由 render 调用渲染。但此时,它还没有附加到 DOM(对吗?)。所以图表调用不幸地死掉了。
这个的模式是什么?我很想知道有一个渲染后回调。我已经尝试了一些解决这个问题的技巧,有时我可以让图表工作,但事件不会绑定(bind)。
最佳答案
我处理这类事情的常用方法是使用 setTimeout
超时为零,以便在浏览器再次获得控制权后安排发生一些事情。试试这个:
render: function() {
$(this.el).html(this.template({title: 'test'}));
var _this = this;
setTimeout(function() {
_this.renderScatterChart();
}, 0);
return this;
}
或者,如果 renderScatterChart
已绑定(bind)到相应的 this
:
render: function() {
$(this.el).html(this.template({title: 'test'}));
setTimeout(this.renderScatterChart, 0);
return this;
}
您还可以使用_.defer
如果您想更明确地说明自己在做什么:
defer
_.defer(function, [*arguments])
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0.
所以你也可以这样做:
// Assuming that `renderScatterChart` is bound to the appropriate `this`...
render: function() {
$(this.el).html(this.template({title: 'test'}));
_(this.renderScatterChart).defer();
return this;
}
// or if it isn't bound...
render: function() {
$(this.el).html(this.template({title: 'test'}));
var _this = this;
_(function() {
_this.renderScatterChart();
}).defer();
return this;
}
关于javascript - 在 BackBone js 中调用 javascript 渲染 View 。渲染后回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145680/