事件发射器不在回调中工作

时间:2014-05-14 13:44:48

标签: node.js express

我尝试运行此代码,一切顺利但事件发射器无效。我只想从路由器检查数据是重复还是保存。

database.js

var mongoose = require( 'mongoose' );
var auths = require('../model/hiren-conf');
var EventEmitter = require("events").EventEmitter;

var ee = new EventEmitter();

exports.create = function(req){
    var instance = new auths.auth();
    if(req.body.tag && req.body.email){
        auths.auth.findOne({ 'tag' : req.body.tag , 'email' : req.body.email}, function(err , duplicate){
            if (!err){
                if(!duplicate){
                    instance.tag = req.body.tag;
                    instance.email = req.body.email;
                    instance.save(function(err){
                        if(!err) console.log('Saved');

                    });
                    ee.emit('Save');

            }       else {
                    console.log("Duplicate");
                    ee.emit('Duplicate');
                };
        } else console.log(err);
        });

        }

    };

路由/ new.js

var express = require('express');

var router = express.Router();
var database = require('./database.js');
var EventEmitter = require("events").EventEmitter;

var ee = new EventEmitter();

router.get('/', function(req, res){
    res.render('newdata', {
        title: 'Add new data'
    })
});

router.post('/', function(req, res){
     database.create(req);
    ee.on('Save', function(){
        console.log('data saved')
    });
    ee.on('Duplicate', function(){
        console.log('Duplicate data')
    });
    res.end();
});

1 个答案:

答案 0 :(得分:2)

您正在两个不同的文件中创建不同的ee对象。

router.post('/', function(req, res){
     database.create(req, ee);//try passing the ee object and use it to emit the event in db.js
    ee.on('Save', function(){
        console.log('data saved')
    });
    ee.on('Duplicate', function(){
        console.log('Duplicate data')
    });
    res.end();
});