Event emitter for function object in separate module

Hi folks,

I have a function myFunction in separate someFile.js file:

var EventEmitter = require("events");

var MyFunction = function() {
    ...
    return this;
}

module.exports = MyFunction; 

I create an object of that function in another js file, and I want to attach an event handler to it:

const MyFunction = require('./lib/ParticleSwarmOptimizer');

var myFunctionObject = MyFunction();
myFunctionObject.on("someEvent", function() {...});

But I keep getting the error "TypeError: myFunctionObject.on is not a function".

I have tried to do it like in this tutorial, like in this tutorial (section "Implement a custom class based on EventEmitter") and like in Node-RED's Node.js file.

But I keep getting the same error over and over again. Still getting nuts from this kind of constructions in Javascript :roll_eyes:

Can somebody correct my code snippet to emit an event in the function, and listen to those events in the handler?

Thanks a lot !!!
Bart

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

function MyEmitter() {
    if (!(this instanceof MyEmitter)) return new MyEmitter();
    EventEmitter.call(this);
    this.init();
}

inherits(MyEmitter, EventEmitter);

Usage...

const myem = require('./my-emitter');
let myEmitter = myem.MyEmitter();
myEmitter.on("event", function() {});

Hey Steve,
It seems to work. Couldn't find it myself.
At those moments I really miss the simple Java syntax ...

Thanks for sharing the code snippet!!

While this is good, I'm liking the singleton class approach myself at the moment. Works really nicely for slightly more complex requirements as embodied now in the web.js and socket.js modules in uibuilder.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.