mardi 12 juillet 2016

Nice javascript pattern for object imbrication (simulate multiple inheritance)

I would like to create a ES6 class with inheritance from 2 classes (from external libraries), but ES6 doesn't allow that. I can't use mixins either. Imbrication seems to be my only option.

For the example, let's say i would like to have a UI component class that directly emits events, log stuff, etc. (for polymorphic purposes).

I would like to avoid the following pattern:

class UIComponent extends React.Component {
    constructor(props) {
        super(props);
        this.ee = new EventEmitter();
    }

    /*
     *   methods of my UIComponent
     */
    emitThis( val ) {
        this.emit('thisEvent', val);
    },

    onThat( func ) {
        this.on('thatEvent', func);
    },

    doThis() {
        this.specificLog("i'm doing this");
        // do stuff
    }

    /*
     *   Here i just implement all methods of EventEmitter...
     */
    on(...args) {
        this.ee.on(...args);
    }

    once(...args) {
        this.ee.once(...args);
    }

    emit(...args) {
        this.ee.emit(...args);
    }

    /* this goes on and on... */
}

Does Javascript (ES5, ES6, ES2015) allow some nicer pattern for this purpose ?

Aucun commentaire:

Enregistrer un commentaire