简体   繁体   English

Google Closure:在容器上设置事件监听器

[英]Google Closure : Setting event listener on container

I have a container lets say a navigation bar at the top. 我有一个容器,可以在顶部说一个导航栏。 I am trying to attach a listener to the entire container from some other module. 我试图从其他模块将侦听器附加到整个容器。 For example the code below creates the entire toolbar. 例如,下面的代码创建了整个工具栏。

 goog.provide('view.ToolBar');

    goog.require('components.ui.Button');
    goog.require('core.TemplatedComponent');
    .
    .
    goog.require('view.KeyboardNavigation');

    /**
     * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
     * @constructor
     * @extends {core.TemplatedComponent}
     */
    view.ToolBar = function(opt_domHelper) {
      // base constructor
      goog.base(this, opt_domHelper);

    };
    goog.inherits(view.ToolBar, core.TemplatedComponent);

    view.ToolBar.prototype.enterDocument = function() {
         new view.KeyboardNavigation(this);
         ../more code and more functions but irrevelant for my question
    }

As you can see I want another module called keyboard navigation to listen on any key events that would happen on the toolbar. 如您所见,我希望另一个称为键盘导航的模块侦听工具栏上可能发生的任何按键事件。 I pass the component to the keyboardNavigator module and then attach a listener to it but its not working. 我将组件传递给keyboardNavigator模块,然后将侦听器附加到该组件,但它无法正常工作。 I am new to google closure and don't know what i am doing wrong. 我是Google封锁的新手,不知道自己在做什么错。 The keyboardNavigation module code is what i have tried below 该键盘导航模块代码是我下面尝试的

goog.provide('view.KeyboardNavigation');

/**
 * @constructor
 * @extends {goog.events.EventHandler}
 */
view.KeyboardNavigation = function(component){
    this.componentContainer = component;
}
goog.inherits(view.KeyboardNavigation, goog.events.EventHandler);

view.KeyboardNavigation.prototype.componentContainer = null;

view.KeyboardNavigation.prototype.enterDocument = function(){
    console.log("1");
    this.listen(this.componentContainer.getElement(),goog.events.EventType.CLICK, goog.bind(this.handleKeyEvent, this), false);
}

view.KeyboardNavigation.prototype.handleKeyEvent = function(event){
    console.log("2");
}

So a few problems at first glance.. One, I think you probably want goog.events.EventTarget not goog.events.EventHandler (which is a very useful class, but is generally used as a member rather than a subclass - EventTarget is the more traditional implementation you're probably thinking of). 乍看之下有几个问题。一个,我想您可能想要goog.events.EventTarget而不是goog.events.EventHandler (这是一个非常有用的类,但通常用作成员而不是子类EventTarget是您可能正在考虑的更传统的实现)。 Two, you don't call super (or rather goog.base ) in your constructor... 第二,您不要在构造函数中调用super (或goog.base )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM