我正在尝试创建两个node.js文件。我正在使用事件发射器模块。当我尝试搜索数据时,我想发出一个事件,以便在从对象数组返回数据之前引发事件。
// event emitter file:
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var _ = require('underscore');
// Custom class
function EmployeeEmitter(args) {
this.data = args;
EventEmitter.call(this);
}
inherits(EmployeeEmitter, EventEmitter);
EmployeeEmitter.prototype.lookupByLastName = function (name) {
this.emit('lookupByLastName',name);
if( _.where(data, {lastName:name}))
{
return _.where(data, {lastName:name})
}
else{
return;
}
};
module.exports.EmployeeEmitter = EmployeeEmitter;
现在这是我的事件发射器,我想在用户搜索数据时触发lookupbylastName。为了测试它,我创建了另一个文件,我使用event.on方法。不幸的是它'没有运行它给我错误我不知道Wats出错了。
//Test file:
var colors = require('colors');
var EmployeeEmitter = require('./employeeEmitter').EmployeeEmitter;
// Usage
var data = [
{id:1, firstName:'John',lastName:'Smith'},
{id:2, firstName:'Jane',lastName:'Smith'},
{id:3, firstName:'John',lastName:'Doe'}
];
var employees = new EmployeeEmitter(data);
employees.on('lookupByLastName', function (args) {
});
console.log("\nLookup by last name (Smith)".red);
console.log(employees.lookupByLastName('Smith'));