我在用着导航网 https://github.com/krasimir/navigo对于一个小网站。用户被要求登录到登陆页面上的帐户,然后在验证其帐户后路由到主模板。
页面对象是从 Firebase 数据库填充的,因此我初始化一个类并将多个事件和页面元素绑定到原型方法,以便user
对象来自firebase.auth()
可以更容易地传递。
我可以在主索引页面上加载并登录。当页面更新模板时,事件处理程序会中断,因为登录页面上不存在元素(个人资料图片等)。当页面尝试更新事件(甚至 HTML 元素)时,引用错误会中断页面加载。
Update
通过使用.then()
等待 firebase 承诺,我可以在身份验证后刷新页面并查看所有更新的数据。但是,初始路由仍然会引发引用错误,因为元素尚未创建。
已验证.html 模板
<!-- language: lang-html -->
<div class="user-view">
<img id="user-pic" class="circle" src="" />
<button id="sign-out-button" class="waves-effect waves-light btn blue">Sign-out</button>
<div id="string-name" class="white-text name"></div>
<div id="user-email" class="white-text email"></div>
</div>
main.js
function MainObj() {
this.userPic = document.getElementById('user-pic');
this.stringName = document.getElementById('string-name');
this.initFirebase()
}
MainObj.prototype.initFirebase = function() {
this.auth = firebase.auth();
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
}
MainObj.prototype.signIn = function() {
var provider = new firebase.auth.GoogleAuthProvider();
this.auth.signInWithPopup(provider).then(user => {
// This navigates after login, but elements still throw reference errors without a full page refresh
router.navigate('main');
});
}
MainObj.prototype.onAuthStateChanged = function(user) {
// user is signed in
if(user) {
router.navigate('main') // route from root to main template
this.userPic.setAttribute('src', user.photoURL);
this.stringName.textContent = user.displayName;
} else {
router.navigate('login') // route back to login
}
}
错误:
Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of null
有没有办法动态加载带有模板文件的脚本,以便在脚本执行之前填充 DOM?