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

时间:2012-07-18 02:24:56

标签: javascript google-closure-library

我的Google Closure代码中有一个函数,其中包含一个事件监听器,旨在将大豆模板生成的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();

然而,它不起作用。 Chrome控制台也不会出错。我试过的是下面的代码,它使用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);

后一种方法有效,但根本不使用Closure,所以我觉得它不可靠。为什么用Google Closure编写的事件监听器无效?

3 个答案:

答案 0 :(得分:0)

你应该停止浏览器事件。

event.stopPropagation();

答案 1 :(得分:0)

您应该将它附加到窗口对象。

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

答案 2 :(得分:0)

如果您在 'window' 对象而不是文档正文上侦听“load”事件,则可以使用 Google Closure。

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

P.S.,很抱歉我的回答晚了 8 年

相关问题