我對這類事情的常用方法是使用setTimeout
,超時時間爲零,以便在瀏覽器再次獲得控制權時安排某些事情發生。試試這個:
render: function() {
$(this.el).html(this.template({title: 'test'}));
var _this = this;
setTimeout(function() {
_this.renderScatterChart();
}, 0);
return this;
}
或者,如果renderScatterChart
已經綁定到相應的this
:
render: function() {
$(this.el).html(this.template({title: 'test'}));
setTimeout(this.renderScatterChart, 0);
return this;
}
您也可以使用_.defer
如果你想更明確的瞭解你在做什麼:
延遲_.defer(function, [*arguments])
次
推遲調用功能,直到當前調用堆棧已被清除,類似於使用的setTimeout與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;
}
OMG。我完全不相信,這工作。 – whatbird 2012-02-05 05:10:38
@whatbird:這個'setTimeout(...,0)'技巧只是建立一個函數,當你的JavaScript全部完成並且控制權返回給瀏覽器時被調用。因此,您的代碼將設置所有內容並將所有內容添加到DOM,然後瀏覽器接管並觸發延遲的功能。這個技巧有點破解,但很有用。 – 2012-02-05 05:51:55
如果您在運行渲染前將view.el插入到DOM中,則不需要破解。我不喜歡使用setTimeout hack,在流量不錯的情況下,它永遠不需要。檢查我的答案,解釋在插入.el之前運行呈現的差異並在插入後運行。一次運行崩潰,另一次正常運行,沒有setTimeout攻擊。 ;) – 2012-07-19 19:51:34