简体   繁体   中英

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. I am new to google closure and don't know what i am doing wrong. 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). Two, you don't call super (or rather goog.base ) in your constructor...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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