javascript - Google Closure EventTarget 如何运作?

标签 javascript events google-closure-compiler google-closure google-closure-library

我在高级编译模式下遇到错误。

Uncaught TypeError: Object #<d> has no method 'attachEvent'

经过一些 source map 魔法后,我发现这是从 goog.events.listen 调用中抛出的,其中第一个参数是我的自定义对象,继承了 goog.events.EventTarget .

这是闭包的来源

goog.events.EventTarget.prototype.addEventListener = function(
    type, handler, opt_capture, opt_handlerScope) {
  goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);
};

所以这个函数在我的对象原型(prototype)上结束,连同 customEvent_ = true,然后在 goog.events.listen

// Attach the proxy through the browser's API
if (src.addEventListener) {
  if (src == goog.global || !src.customEvent_) {
    src.addEventListener(type, proxy, capture);
  }
} else {
  // The else above used to be else if (src.attachEvent) and then there was
  // another else statement that threw an exception warning the developer
  // they made a mistake. This resulted in an extra object allocation in IE6
  // due to a wrapper object that had to be implemented around the element
  // and so was removed.
  src.attachEvent(goog.events.getOnString_(type), proxy);
}

(最后一行是抛出的)

这不应该导致堆栈溢出吗?如果我的对象从 EventTarget 继承 addEventListener,为什么它会进入 else 分支?在简单编译模式下,一切正常。这是如何工作的,为什么我只在高级编译模式下收到错误?

最佳答案

你能再添加一些代码吗?您的自定义事件是什么样的?基本上,JS 中默认的“addEventListener”被重写了。 IE没有实现addEventListener,只是attachEvent,返回的事件对象不是普通事件,而是一个goog.events.BrowserEvent .

在高级编译模式下,编译器展平(缩小)所有对象的属性,包括事件对象。您的自定义事件的属性可能会在高级编译模式下变平(这里很可能是这种情况),因此原型(prototype)中不存在 attachEvent() 。它可能变成了 aE() 或类似的东西。在任何人能够提出真正有用的建议之前,再添加一些代码。

关于javascript - Google Closure EventTarget 如何运作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522174/

相关文章:

javascript - 单击 Angular 4 中的按钮时动态添加输入

javascript - 使用 reactjs 导入 Css 显示错误 "Unclosed string"

javascript - 鼠标悬停在贝塞尔曲线上

jquery 元素隐藏时触发函数

javascript - 闭包编译器删除的内容超出了我想要删除的内容

javascript - 过滤器 "orderBy"无法将变量用作数组

javascript - onclick 永久更改 html 标题的边框颜色,直到单击另一个标题

php 选择并显示按分钟、小时、天排序的 sql 信息

javascript - 我如何告诉 Google 闭包编译器不要删除 var