【问题标题】:Why is my event listener written in Google Closure not working?为什么我用 Google Closure 编写的事件监听器不起作用?
【发布时间】:2012-07-18 02:24:55
【问题描述】:

我的 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 编写的事件监听器不起作用?

【问题讨论】:

    标签: javascript google-closure-library


    【解决方案1】:

    你应该停止浏览器事件。

    event.stopPropagation();

    【讨论】:

      【解决方案2】:

      你应该把它附加到窗口对象上。

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

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-11
          • 2015-06-06
          • 2013-03-28
          • 2020-05-08
          • 2011-11-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多