Callum Linington
Callum Linington

Reputation: 14417

EventEmitter JavaScript

This code block emits an event and passes through an integer:

function executeEvent() {
    // here you could use the event bus to chuck the pfio event to the pfio event api.....

    if (eventQueue.length > 0) {
        for (var i = 0; i < eventQueue.length; i++) {
            var event = eventQueue[i];

            if (event.processing){
                console.log(colors.yellow("Already processing event"));
                continue;
            }
            else
                event.processing = true;

            eventBus.emit('event.process', i);
        }
    }

    setImmediate(executeEvent.bind(this));
};

However, when it gets to picking up the Event:

eventBus.on('event.process', processEvent);

function processEvent(index) {
    console.log("Processing %s %d", colors.yellow("Event"), colors.red(index.toString()));

    var event = getEvent(index);

    var current = new Date().getTime(); // get the number of milliseconds from 1/1/1970

    var fireEvent = false;

    if (event.eventType == 2) // timer or interval respectively
        fireEvent = current - event.init.getTime() >= event.when;

    if (event.eventType == 3) // schedule
        fireEvent = current >= event.when;

    if (fireEvent)
        eventBus.emit('event.fire', event);
    else
        event.processing = false;
}

function getEvent(index){
    return eventQueue[index];
}

The index is NaN. Please could someone tell me where the error be? I'm guessing it may be in the on event of the event bus.

Upvotes: 0

Views: 472

Answers (1)

badsyntax
badsyntax

Reputation: 9650

Change

console.log("Processing %s %d", colors.yellow("Event"), colors.red(index.toString()));

to

console.log("Processing %s %s", colors.yellow("Event"), colors.red(index.toString()));

Although index is an integer when it enters the function, the returned value of colors.red(index.toString()) is no longer an integer, and the %d substitution string will attempt to typecast to an integer, thus resulting in NaN.

Upvotes: 2

Related Questions