简体   繁体   中英

Best way using events in node.js

Which is the best approach for listening/launching events in node.js? I've been testing event launching and listening in node.js by extending the model with EventEmitter and I'm wondering if it has sense this approach since the events are only listened when there is a instance of the model. How can be achieved that events will be listened while the node app is alive??

Example for extending the model using eventEmitter.

// myModel.js

var util = require('util');
var events2 = require('events').EventEmitter;
var MyModel = function() {

        events2.call(this);
        // Create a event listener
        this.on('myEvent', function(value) {
            console.log('hi!');
        });
    };

MyModel.prototype.dummyFunction = function(params) {
// just a dummy function.

}

util.inherits(MyModel, events2);
module.exports = MyModel;

EDIT: A more clear question about this would be: how to keep a permanent process that listens the events during the app execution and it has a global scope (something like a running event manager that listens events produced in the app). Would be a solution to require the file myModel.js in app.js? How this kind of things are solved in node.js?

I'm not entirely sure what you mean about events only being active when there is an instance of a model since without something to listen and react to them, events cannot occur.

Having said that, it is certainly reasonable to:

util.inherits(global,EventEmitter)
global.on('myEvent',function(){
    /* do something useful */
});

which would allow you to:

global.emit('myEvent')

or even:

var ee=new EventEmitter();

ee.on('myEvent',...)

As for how to properly use EventEmitter: it's defined as

function EventEmitter() {}

which does not provide for initialization, so it should be sufficient to:

var Thing=function(){};
util.inherits(Thing,EventEmitter);

which will extend instances of Thing with:

  • setMaxListeners(num)
  • emit(type,...)
  • addListener(type,listener) -- aliased as on()
  • once(type,listener)
  • removeListener(type,listener)
  • removeAllListeners()
  • listeners(type)

The only possible "gotcha" is that EventEmitter adds its own _events object property to any extended object ( this ) which suggests you should not name any of your own object properties with the same name without unexpected behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM