1. 程式人生 > >Nodejs:事件機制

Nodejs:事件機制

UserBean.js

var events = require("events");
var http = require("http");

function UserBean() {
    this.eventEmit = new events.EventEmitter();
    this.zhuce = function (req, res) {
        console.log('註冊');
        req['uname'] = 'jack';
        req['pwd'] = 'bb';

        this.eventEmit.emit('zhuceSuc', 'aa', 'bb');//丟擲事件訊息
    },
        this.login = function (req, res) {
            console.log("登入");
            res.write("使用者名稱:" + req['uname']);
            res.write("密碼:" + req['pwd']);
            res.write("登入");
        }
}
module.exports = UserBean;

demo.js

var http = require('http');
var events = require("events");
var UserBean = require('./model/UserBean');

http.createServer(function (request, response) {
    response.writeHead(200, {
        'Content-Type': 'text/html;        charset=utf-8'
    });
    if (request.url !== "/favicon.ico") { //清除第2此訪問
        user = new UserBean();
        user.eventEmit.once("zhuceSuc", function (uname, pwd) {//zhuceSuc:事件名稱
            response.write("註冊成功");
            console.log('傳來uname:' + uname);
            console.log('傳來pwd:' + pwd);
            user.login(request, response);
            response.end('');
        });//註冊監聽
        user.zhuce(request, response);
    }
}).listen(8000);
console.log('Server running  at http://127.0.0.1:8000/');