DomingoSL
DomingoSL

Reputation: 15494

How to attach parameters to a nodejs event emmiter

I've developed a way to make two separate services to comunicate using a pub/sub channel using Redis, this is the main part of the code:

var Intercom = (function () {
    var _event = new events.EventEmitter();

    listener.subscribe("intercom");
    listener.on("message", function(channel, message) {
        try {
            var data = JSON.parse(message);
            _event.emit(data.controller, data.payload);
        }
        catch (e) {}

    });

    return {
        on: function (evt, callback) {
            _event.on(evt, callback);
        },
        emit: function (controller, payload) {
            try {
                sender.publish("intercom", JSON.stringify({ controller: controller, payload: payload})); 
            }
            catch (e) {}
        }

    }
})();

Im using it on the main app just by: intercom.on('hook', hookController.main); As you can see, if the query is "hook" the main() function of hookController is called. Its a very ExpressJs like approach.

The hookController does a very simple thing:

exports.main = function(req) {
    console.log(req);
}

It is not very clear to my how the parameter "req" is getting passed to main(), and probably because of my lack of understanding about it, I cant figure it out how to pass another parameter to main from the main app, something like:

var foo = 'bar';
intercom.on('hook', hookController.main, foo);

Upvotes: 0

Views: 52

Answers (1)

DomingoSL
DomingoSL

Reputation: 15494

I found a way to do it;

var foo = 'bar';
intercom.on('hook', function(req) { hookController.main(req, foo) });

Its a little bit ugly.

Upvotes: 1

Related Questions