简体   繁体   English

为什么我用 Google Closure 编写的事件侦听器不起作用?

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

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:我的 Google Closure 代码中有一个函数,它带有一个事件侦听器,旨在在主体加载时将 soy 模板生成的 HTML 附加到主体:

/**
 * 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. Chrome 控制台也没有错误提示。 What I have tried is the below code, which uses the addEventListener function native to javascript.我试过的是下面的代码,它使用了 javascript 原生的 addEventListener 函数。

... 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.后一种方法可以,但是根本没有用到Closure,所以感觉不靠谱。 Why is my event listener written in Google Closure not working?为什么我用 Google Closure 编写的事件侦听器不起作用?

you should stop the browser events.你应该停止浏览器事件。

event.stopPropagation();事件.stopPropagation();

You should attach it to the window object.您应该将它附加到窗口对象。

goog.events.listenOnce(
  window
, goog.events.EventType.LOAD
, function(){
    window.alert( 'Ready for ADVANCED_COMPILATION!' );
  }
);

You can use Google Closure if you listen for a "load" event on the 'window' object instead of the document body.如果您在“窗口”对象而不是文档主体上侦听“加载”事件,则可以使用 Google Closure。

Try this: goog.events.listen(window, "load", function(){//code })试试这个: goog.events.listen(window, "load", function(){//code })

PS, I'm sorry that my answer is 8 years late PS,很抱歉我的回答晚了8年

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM