blendsdk / blend-class-system

Easy OOP class-system for JavaScript
MIT License
4 stars 0 forks source link

Question: Blend class inherit from EventEmitter #3

Closed alexandrubau closed 8 years ago

alexandrubau commented 8 years ago

Is it possbile to use a Blend Class to inherit methods from Node.js's EventEmitter module?

Blend.defineClass('App.service.Name', {
  singleton: true,
  init: function(){
    // call parent stuff
    var EventEmitter = require('events');
    util.inherits(this, EventEmitter);
  }
});

App.service.Name.emit('event'); // will this work?

App.service.Name.on('ready', function(){ console.log('emitted'); });

Thanks

blendsdk commented 8 years ago

Let me check, I will get back to you a.s.a.p.

alexandrubau commented 8 years ago

I ended up making a mixin like so:

Blend.defineClass('App.mixin.Observable', {

    /**
     * Maps to event emitter
     */
    on: function(){

        if( !this.event ){

            var EventEmitter = require('events').EventEmitter;

            this.event = new EventEmitter;
        }

        this.event.on.apply(this.event, arguments);
    },

    /**
     * Maps to event emitter
     */
    emit: function(){

        if( !this.event ){

            var EventEmitter = require('events').EventEmitter;

            this.event = new EventEmitter;
        }

        this.event.emit.apply(this.event, arguments);
    }
});

You think it's a good approach? What I don't like is that I have to duplicate each method (on, emit, addListener, etc.).

blendsdk commented 8 years ago

I was about the suggest the same approach :) At the moment the ClassBuilder cannot "mix" non-blend classes. ClassBuilder.js:338.

On the side track, your requirement gave me the idea to create a Dependency Injection Container :)

alexandrubau commented 8 years ago

Nice. Thanks for your time.

alexandrubau commented 8 years ago

I've also noticed that the init() method is not called for mixins. Is this the intended behaviour? It would be nice to have it called, to place some initialization logic, this way avoiding the duplicate code.

if( !this.event ){

            var EventEmitter = require('events').EventEmitter;

            this.event = new EventEmitter;
        }
blendsdk commented 8 years ago

That behavior is intentional because, the class-system will not be able to decide "when" to and in which order to call the mixin's init method. Imagine you have multiple mixins and one depends on the other.