您好我正在尝试像这样构建一个Node.js应用程序。我的app.js文件中的代码是:
var _ = require('underscore');
var employee = require('./employeeEmitter');
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var inherits = require('util').inherits;
var data = [
{id:1, firstName: 'John', lastName: 'Smith'},
{id:2, firstName: 'Jane', lastName: 'Smith'},
{id:3, firstName: 'John', lastName: 'Doe'}
];
inherits(employee.EmployeeEmitter, EventEmitter);
var newEmployeeEmitter = new employee.EmployeeEmitter(data);
newEmployeeEmitter.on('lookupById',function(){newEmployeeEmitter.lookupById(newEmployeeEmitter.data,1)});
employee.EmployeeEmitter.prototype.test= function () {
this.emit('lookupById');
}
console.log(newEmployeeEmitter.test);
在我的employeeEmitter.js文件中:
var _ = require('underscore');
var EventEmitter = require('events').EventEmitter;
module.exports = {
EmployeeEmitter: function (args) {
this.data = args;
EventEmitter.call(this);
},
lookupById : function(data,id){
var foundId = _.where(data,{id:id});
return foundId[0];
},
lookupByLastName : function(data,lastName) {
return _.where(data,{lastName: lastName});
},
addEmployee: function (data, firstName, lastName) {
// obtain next id
var newId = function (data) {
var id = _.max(data, function (data) {
return data.id;
});
return id.id + 1;
}
// return new data (old data + new object, but without mutation of initial object)
data.push( {id:newId(data), firstName: firstName, lastName: lastName });
return data;
}
}
我希望当我运行app.js时,控制台窗口中的输出应为:
{id:2,firstName:' Jane',lastName:' Smith' }
然而,它显示[功能]。我不知道会发生什么。谁能帮我? 非常感谢你!
答案 0 :(得分:-1)
您实际上没有调用测试功能,当您发出事件时,他们不会返回任何内容。
更像这样的东西可能有用:
var _ = require('underscore');
var employee = require('./employeeEmitter');
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var inherits = require('util').inherits;
var data = [
{id:1, firstName: 'John', lastName: 'Smith'},
{id:2, firstName: 'Jane', lastName: 'Smith'},
{id:3, firstName: 'John', lastName: 'Doe'}
];
inherits(employee.EmployeeEmitter, EventEmitter);
var newEmployeeEmitter = new employee.EmployeeEmitter(data);
newEmployeeEmitter.on('lookupById',function(){console.log(newEmployeeEmitter.lookupById(newEmployeeEmitter.data,1));});
employee.EmployeeEmitter.prototype.test= function () {
this.emit('lookupById');
}
newEmployeeEmitter.test();