问题
I'm using navigo.js for a small website. Users are asked to log in to an account on a landing page and then routed to the main template once they've authenticated their account.
The page objects are populated from a Firebase database, so I initialize a class and bind several events and page elements to prototype methods so the user
object from firebase.auth()
can be passed around more easily.
I'm able to load and login on the main index page. When the page updates the template, event handlers break because the elements don't exist on the login page (profile picture, etc). When the page tries to update events (or even HTML elements), reference errors break the page load.
Update
By using .then()
and waiting for the firebase promise, I can refresh the page after authenticating and see all data updated. However, the initial routing still throws reference errors because the elements haven't been created yet.
authenticated.html template
<!-- 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
}
}
The error:
Uncaught (in promise) TypeError: Cannot read property 'addEventListener' of null
Is there a way to dynamically load scripts with template files so the DOM is populated before the script executes?
来源:https://stackoverflow.com/questions/50764123/event-binding-with-router