呼吁渲染骨干JS的看法的JavaScript。渲染后的回调? [英] calling javascript on rendering views in BackBone js. post-render callback?
问题描述
忽然,一个骨干视图渲染电话:
behold, a backbone view render call:
render: function() {
$(this.el).html(this.template({title: 'test'})); //#1
this.renderScatterChart();
return this;
},
所以,我所说的标准呈现在#1。然后,我调用一个方法[这一次,它是图表LIB包装]认为寻找一个div。在div被渲染调用呈现。但在这一点上,它不附着到DOM还(右?)。因此,图调用黯然死去。
so, I call a standard render at #1. and then, i call a method [this time, it is a wrapper for charting lib] that looks for a div. the div is rendered by the render call. but at this point, it is not attached to the DOM yet (right?). so the chart call sadly dies.
究竟是什么模式?我很想听到,有一个后呈现回调。我试过围绕这几个黑客,有时我得到的图表工作,但事件不绑定。
what is the pattern for this? i'd love hear that there is a post-render callback. i've tried a few hacks around this, and sometimes i get the chart to work, but events don't bind.
推荐答案
我对这种事情通常的方法是使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout\"><$c$c>setTimeout$c$c>为零的超时时间,安排一些事情发生一次浏览器再次获得控制。试试这个:
My usual approach for this sort of thing is to use setTimeout
with a timeout of zero to arrange for something to happen once the browser gets control again. Try this:
render: function() {
$(this.el).html(this.template({title: 'test'}));
var _this = this;
setTimeout(function() {
_this.renderScatterChart();
}, 0);
return this;
}
或者,如果 renderScatterChart
已经绑定到相应的这个
:
render: function() {
$(this.el).html(this.template({title: 'test'}));
setTimeout(this.renderScatterChart, 0);
return this;
}
您也可以使用 _。推迟
如果你想更明确你在做什么:
You can also use _.defer
if you want to be more explicit about what you're up to:
延迟 _。推迟(函数,[*参数])
推迟调用的功能,直到当前调用堆栈已被清除,类似于使用的setTimeout 0的延迟。
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0.
所以,你也可以做这样的:
So you could also do it like this:
// 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;
}
这篇关于呼吁渲染骨干JS的看法的JavaScript。渲染后的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!