[英]Click event in event listener written in Google Closure not working?
[英]Why is my event listener written in Google Closure not working?
我的 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();
但是,它不起作用。 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 编写的事件侦听器不起作用?
你应该停止浏览器事件。
事件.stopPropagation();
您应该将它附加到窗口对象。
goog.events.listenOnce(
window
, goog.events.EventType.LOAD
, function(){
window.alert( 'Ready for ADVANCED_COMPILATION!' );
}
);
如果您在“窗口”对象而不是文档主体上侦听“加载”事件,则可以使用 Google Closure。
试试这个: goog.events.listen(window, "load", function(){//code })
PS,很抱歉我的回答晚了8年
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.