Search code examples
javascriptoopdesign-patternsobserver-pattern

Subscriptions inside constructors


This question relates specifically to JavaScript, but I imagine would apply to any language.

I am new to OOP and I'm just looking to see if there is a best practice/better way of doing this. I have an object that needs to subscribe to some events. I put the event subscriptions inside the objects constructor, like so:

function Obj() {
    //instance variables

    outsideEvent.addHandler(function(response) {
        //do stuff
    });
}

The problem is that now I feel like the object is coupled to the publisher; I would like if I could somehow subscribe outside of the object itself. Unfortunately I don't know when or where a new instance of this object might be initialized. I thought about making an "attachEvents" member function, but that function would have to be called whenever a new instance is made or called in the constructor, but maybe that is a best practice? It would at least make it easier to unit test.

I'm just looking for some advice; anything is appreciated!


Solution

  • function Constructor(eventEmitter) {
        /* code */
        this.listenTo(eventEmitter);
    }
    
    Constructor.prototype.listenTo = listenTo;
    
    function listenTo(eventEmitter) {
        /* bind events */
    }
    

    Alternatively rather then passing an eventEmitter into your constructor, your constructor can inherit from eventemitter and be one itself.

    This means it can listen on itself. You would then publish events on it rather then some external eventEmitter.