Why is my event listener written in Google Closure not working?

社会主义新天地 提交于 2019-12-13 16:02:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!