Google Closure EventTarget如何运作?

时间:2012-07-17 12:11:43

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

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

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

在一些源地图魔术之后我发现这是从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);
};

因此,此函数最终会在我的对象原型上与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);
}

(最后一行是投掷的那一行)

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

1 个答案:

答案 0 :(得分:1)

您可以添加更多代码吗?您的自定义活动是什么样的?基本上,JS的默认'addEventListener'被重写。 IE没有实现addEventListener,但只有attachEvent和返回的事件对象不是普通事件,而是goog.events.BrowserEvent

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

相关问题