javascriptevent-handlinggoogle-closure-library

Google Closure equivalent of jQuery's ".on()"


I'm working with a project in Google Closure, and I'd like to attach event listeners to query selectors so that they apply likewise to dynamically added elements. If I were using jQuery, I might do something like:

$(document).on('click', '.targetclass', function(e) {...});

I've been unable to find any documentation on a similar capability in the Google Closure library. I suppose such a thing could be easily built in which you can register handlers to some global list of handlers, but given how common this pattern is I'd be very surprised if I was not re-inventing the wheel.

Is there such a thing in Google Closure?


Solution

  • Have a look at the following code that will provide you as a reference.

    Usually, event handlers are put under the enterDocument function that is inherited from goog.ui.Component. targetEl_ is dyanamically added inside createDom() and the event handler is attached after it enters the DOM.

    // sample.js    
    goog.provide('my.page.Sample');
    
    
    goog.require('goog.dom');
    goog.require('goog.ui.Component');
    
    /**
     * @constructor
     * @returns {my.page.Sample}
     */
    my.page.Sample = function() {
        goog.base(this);
        this.targetEl_ = null;
    };
    goog.inherits(my.page.Sample, goog.ui.Component);
    
    
    /** 
     * Creates the DOM elements and appends to the element referred while calling render() in test.js
     * @inheritDoc
     */
    my.page.Sample.prototype.createDom = function() {
        this.targetEl_ = goog.dom.createDom(goog.dom.TagName.DIV, {"class": "targetElClass"});
        this.setElementInternal(targetEl_); 
    };
    
    /** 
     * Called after the components elements are known to be in the document.
     * @inheritDoc
     */
    my.page.Sample.prototype.enterDocument = function() {
        goog.base(this, 'enterDocument');
        goog.events.listen(this.targetEl_, goog.events.EventType.CLICK, this.handleClicked_, false, this);
    
    };
    
    /**
     * @private
     * @param  {Event} event
     */
    my.page.Sample.prototype.handleClicked_ = function(event) {
        // Handle the event here.
    };
    
    
    // test.js
    
    goog.provide('my.page.Test');
    
    goog.require('my.page.Sample');
    test.init = function(sel) {
        var el = document.querySelector(sel);
        var myPage = new my.page.Sample();
        myPage.render(el);
    };