Javascript window.onload不等待dom就绪
尽管将app.js中的代码包装到window.onload函数中,我还是不断地得到错误Javascript window.onload不等待dom就绪,javascript,backbone.js,ecmascript-6,Javascript,Backbone.js,Ecmascript 6,尽管将app.js中的代码包装到window.onload函数中,我还是不断地得到错误 Cannot set property 'innerHTML' of undefined 由在索引路由上创建HomeView触发。HomeView的render函数尝试在render函数中将模板设置为el的innerHtml this.el.innerHTML = this.template(); 当我使用一些ES6时,这段代码也使用babeljs进行转换,并放在一个文件(bundle.js)中 在尝试w
Cannot set property 'innerHTML' of undefined
由在索引路由上创建HomeView触发。HomeView的render函数尝试在render函数中将模板设置为el的innerHtml
this.el.innerHTML = this.template();
当我使用一些ES6时,这段代码也使用babeljs进行转换,并放在一个文件(bundle.js)中
在尝试window.onload函数之前,我使用了ES6风格的dom ready将代码包装到app.js中
$(() => {
});
如何才能真正确保dom已就绪,或者如何将HomeView的el设置为特定的dom节点
app.js
window.onload = function() {
window.myRouter = new MyRouter();
$(window).on("hashchange", myRouter.hashChange);
Backbone.history.start({pushState: true})
}
export class MyRouter extends Router {
constructor(){
this.routes = {
'': 'index'
}
this._bindRoutes();
}
index(){
this.loadView(new HomeView());
}
main.js
window.onload = function() {
window.myRouter = new MyRouter();
$(window).on("hashchange", myRouter.hashChange);
Backbone.history.start({pushState: true})
}
export class MyRouter extends Router {
constructor(){
this.routes = {
'': 'index'
}
this._bindRoutes();
}
index(){
this.loadView(new HomeView());
}
HomeView
export class HomeView extends View {
constructor(){
$("body").html(this.el);
this.template = _.template($('#main-template').html());
this.render();
super();
}
render(){
this.el.innerHTML = this.template();
使用
而不是
window.onload
问题不在于
onload
。您只需在属性存在之前访问它
在您的
HomeView
构造函数中,您从未设置this.el
:
$("body").html(this.el);
this.template = _.template($('#main-template').html());
this.render();
您正在调用this.render()
,它可以访问this.el.innerHTML
,但是在这三行中您在哪里设置this.el
?没有
如果this.el
应该由View
设置,那么您必须在访问this
之前调用父构造函数:
constructor() {
super();
$("body").html(this.el);
this.template = _.template($('#main-template').html());
this.render();
}
您从未在
HomeView
中设置this.el
。如果它应该由视图设置
,那么您必须在访问此
之前调用父构造函数。是的,非常确定您应该在某个地方有此。_super()
。此外,这与是否加载DOM无关this.el
在任何时候被赋值时都会有一个与DOM加载无关的值。请解释为什么这样可以解决问题window.onload的调用甚至晚于$(document.ready
),所以我不明白为什么这个开关会有帮助。