简体   繁体   中英

Emitting an event in Node.js

I have a Library that uses sockets that I'm trying to edit to emit an event, broadly the code looks like this:

function Library(port, host) {
  this.myData = [];
  this.socket = net.connect( ... );
  this.socket.on('data', this._ondata.bind(this));
  this.socket.on('error', this._onerror.bind(this));
  this.socket.on('close', this._onclose.bind(this));
}
Library.prototype._ondata = function() {
  //do stuff
  //have the data we want
  this.myData.push(stuff);
  this.socket.end();
}
Library.protoype._onclose = function() {
  console.log('this gets logged');
}
modules.export = Library;

I want to emit an event in the _onclose method such that I could do something like

var lib = new Library(port, host);
lib.on('emitted-event', function() {
  var data = lib.myData;
});

because if I just access lib.myData straight away it's still an empty array. But I'm struggling to emit an event. What I'm getting at the moment is Library has no method on. So clearly I'm not adding an emitter in the right way. Anyone know what that is?

You need to use Node's built in events library.

var EventEmitter = require('events').EventEmitter,
    util = require('util');

function Library(port, host) {
  (...)
}

Library.protoype._onclose() = function() {
  this.emit('emitted-event');
}

util.inherits(Library, EventEmitter);

Then you'd do:

var lib = new Library(port, host);
lib.on('emitted-event', function() {
  var data = lib.myData;
});

Ben Fortune's answer would work. Howeever:

var EventEmitter = require('events').EventEmitter
var util = require('util')

function Library(port, host){
  var self = this; //probably want to add this.  if you call from any other function you want proper "this"
  EventEmitter.call(this);
  ...
  var myobj = { eaten: [burger, fries] };
  self.emit('blurp', myobj);
}
util.inherits(Library, EventEmitter)
exports = module.exports = Library; // or new Library(); if you want a singleton

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