Reputation: 824
I'm trying to make a module with an even that I could call from the index file (after a require).
My code includes var events = require("events");
and I've wrote only the tricky part here.
var reqw = require('./module.js');
reqw.on('data', function(d) {
console.log(d);
});
module.exports = {
listaccts: function() {
events.EventEmitter.call(this);
}
}
util.inherits(exports.listaccts, events.EventEmitter);
exports.listaccts.prototype.listme = function() {
thisList = this;
var req = https.request(requestOptions, function(res) {
res.on('data', function(chuck) {
store = chuck;
});
res.on('end', function(d) {
thisList.emit("data", store.toString());
});
});
}
Searched the whole we and yet to find a proper answer..
Upvotes: 1
Views: 3830
Reputation: 971
Modified your code slightly :
module.js
function listaccts(){
}
util.inherits(listaccts, EventEmitter);
listaccts.prototype.listMe = function(){
var self = this;
var store = [];
console.log('here');
var req = https.request(requestOptions, function(res) {
res.on('data', function(chuck) {
console.log('data');
store.push(chuck);
});
res.on('end', function() {
console.log('end');
self.emit("data", store);
});
});
req.end();
};
module.exports = listaccts;
index.js
var reqw = require('./module');
var obj = new reqw();
obj.listMe();
obj.on('data', function(err, data) {
console.log(err);
});
req.end
is important, I have forgot to include and got a never-ending cycle.
Created instance for binding this
, so no need for EventEmitter.call
.
Maybe you want to the listMe
function to inside your constructor.
Hope this help.
Upvotes: 1