Search code examples
javascriptrequirejsecmascript-6browserify

Don't invoke inherited method twice in ES6 classes


I'm moving from RequireJS to browserify (together with babelify) and try to rewrite my current modules to classes. For each of my RequireJS modules I have a method called eventHandler which handles all module specific events. Now when I extend a class, the parent class calls the subclass`s eventHandler method which leads to invoking the method twice.

Parent class:

'use strict';

class Tooltip {
    constructor() {
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
    }
}

module.exports = Tooltip;

Subclass:

'use strict';

import Tooltip  from './Tooltip';

class Block extends Tooltip {
    constructor() {
        super();
        this.eventHandler();
    }

    eventHandler() {
        // Module specific events
        // Gets called twice
    }
}

module.exports = Block;

I liked the fact that the eventHandler method was named the same across all modules as it was easier to maintain. That's why I'd like to keep this pattern. So what would be the best way to solve this problem? Thanks for any suggestions!


Solution

  • Since you know the parent constructor calls this.eventHandler, don't do so in the derived classes:

    'use strict';
    
    import Tooltip  from './Tooltip';
    
    class Block extends Tooltip {
        constructor() {
            super();
            // (No call here)
        }
    
        eventHandler() {
            // Module specific events
            // Gets called twice
        }
    }
    
    module.exports = Block;
    

    Re your comment:

    The parent classes don't always implement an eventHandler method. So I need to ensure it gets called in this case as well.

    Where they do, don't do the call. Where they don't, do do the call. Subclasses are very tightly bound to superclasses, by their nature.

    If you can assume (!) that the presence of eventHandler in the super means it has called it from its constructor, you could do something like this:

    constructor() {
        super();
        if (!super.eventHandler) {
            this.eventHandler();
        }
    }
    

    ...but again, the nature of the super/sub relationship is that it's very tightly-bound, so relying on your knowledge of whether the super does this or not is reasonable.