问题
I have a function in my Google Closure code with an event listener that aims to append HTML generated by a soy template to the body when the body loads:
/**
* Constructs the home page.
*/
AppLoader.prototype.constructHomePage = function() {
goog.events.listen(document.body, 'onload', function() {
document.body.innerHTML = templates.home.main();});
}
(new AppLoader()).constructHomePage();
However, it does not work. Chrome Console also offers no errors. What I have tried is the below code, which uses the addEventListener function native to javascript.
... class instantiation
/**
* Constructs the home page.
*/
AppLoader.prototype.constructHomePage = function() {
document.body.innerHTML = templates.home.main();
}
document.body.addEventListener('load', function() {
(new AppLoader()).constructHomePage();
}, false);
This latter method works, but does not use Closure at all, so I don't feel that it is reliable. Why is my event listener written in Google Closure not working?
回答1:
you should stop the browser events.
event.stopPropagation();
回答2:
You should attach it to the window object.
goog.events.listenOnce(
window
, goog.events.EventType.LOAD
, function(){
window.alert( 'Ready for ADVANCED_COMPILATION!' );
}
);
来源:https://stackoverflow.com/questions/11533486/why-is-my-event-listener-written-in-google-closure-not-working