user3601166
user3601166

Reputation: 127

Code efficiency in Node.js for multiple events listeners

I have a code that emits and handles events in same .js file. Emitting events can be of type "hello", "world", "user", etc as an example. All the event handler functions (.on) have similar approach to handle events inside core functions of error and callbacks (exactly same). Is there a suggestion to refactor and improve the redundant code.

localEvents.on("hello", function(request , reply){
    console.log("inside event for hello");
    hello.intialize() {
       // handle initialise error and callback //
    };
});

localEvents.on("world", function(request , reply){
    console.log("inside event for world");
    world.initialise() {
       // handle initialise error and callback //
    };
});

localEvents.on("user", function(request , reply){
    console.log("inside event for user");
    user.initialise() {
       // handle initialise error and callback //
    };
});

localEvents.emit(task, request, reply);

Upvotes: 5

Views: 7058

Answers (2)

Kushal
Kushal

Reputation: 1360

A simple way of doing this - This way will be more flexible to any changes that you might need to make in the events callback functions

var eventsList = {
    "hello": function(request, reply) {
        console.log("inside event for hello");
        hello.initialise() {
            // handle initialise error and callback //
        };
    },
    "world": function(request, reply) {
        console.log("inside event for world");
        world.initialise() {
            // handle initialise error and callback //
        };
    },
    "user": function(request, reply) {
        console.log("inside event for user");
        user.initialise() {
            // handle initialise error and callback //
        };
    }
}

function generateEvents(events){
    for(var e in events){
        localEvents.on(e, events.e)
    }
}

generateEvents(eventsList)

Upvotes: 1

mscdex
mscdex

Reputation: 106736

You could create a helper function, like:

function addHandler(evName, obj) {
  localEvents.on(evName, function(request, reply) {
    console.log("inside event for %s", evName);
    obj.initialise(function(err) {
       // handle initialise error and callback
    });
  });
}

Then just call it like:

addHandler('hello', hello);
addHandler('world', world);
addHandler('user', user);

Or if you really want to cut down on even the repetition in the arguments you might create a helper like:

function addHandler(evName) {
  var obj = eval(evName);
  localEvents.on(evName, function(request, reply) {
    console.log("inside event for %s", evName);
    obj.initialise(function(err) {
       // handle initialise error and callback
    });
  });
}

Allowing you to then to simply do:

addHandler('hello');
addHandler('world');
addHandler('user');

Upvotes: 5

Related Questions